FragmentStateAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT 怎么用
时间: 2023-08-12 21:09:03 浏览: 50
`FragmentStateAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT` 是一个常量,用于指定 FragmentStateAdapter 的行为。它指定了只有当前可见的 Fragment 才会保持生命周期状态,其他 Fragment 的生命周期状态会被销毁。
使用方法如下:
1. 在创建 FragmentStateAdapter 对象时,使用 `FragmentStateAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT` 常量作为参数:
```java
FragmentStateAdapter adapter = new MyFragmentStateAdapter(getSupportFragmentManager(), FragmentStateAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
```
2. 在自定义的 FragmentStateAdapter 类中,重写 `getItemId()` 方法,确保返回一个唯一的标识符:
```java
public class MyFragmentStateAdapter extends FragmentStateAdapter {
public MyFragmentStateAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment createFragment(int position) {
// 创建 Fragment
}
@Override
public long getItemId(int position) {
// 返回一个唯一的标识符
return position;
}
}
```
这样就可以使用 `FragmentStateAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT` 来保持当前可见的 Fragment 的生命周期状态了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)