模拟fragment重建
时间: 2023-11-28 18:06:06 浏览: 32
您好!如果您想模拟Fragment重建的情况,可以通过以下步骤实现:
1. 在Activity中添加一个Fragment,并保存其实例状态:
```
MyFragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment, "my_fragment_tag")
.addToBackStack(null)
.commit();
// 保存Fragment实例状态
getSupportFragmentManager().putFragment(
savedInstanceState, "my_fragment_key", fragment);
```
2. 在Fragment中添加一些状态信息,例如一个计数器:
```
public class MyFragment extends Fragment {
private int mCounter = 0;
// ...
}
```
3. 在Fragment中重写onSaveInstanceState()方法,保存计数器的状态:
```
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter_key", mCounter);
}
```
4. 在Fragment中重写onActivityCreated()方法,恢复计数器的状态:
```
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mCounter = savedInstanceState.getInt("counter_key");
}
}
```
5. 在Activity中添加一个按钮,点击后更新Fragment中的计数器:
```
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyFragment fragment = (MyFragment) getSupportFragmentManager()
.findFragmentByTag("my_fragment_tag");
if (fragment != null) {
fragment.mCounter++;
Toast.makeText(MainActivity.this,
"Counter: " + fragment.mCounter, Toast.LENGTH_SHORT).show();
}
}
});
```
6. 在Activity中添加一个CheckBox,勾选后切换UI模式:
```
findViewById(R.id.checkbox).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
recreate();
}
});
```
在切换UI模式时,调用Activity的recreate()方法,会销毁并重建Activity和其中的Fragment。通过保存和恢复Fragment的实例状态,可以确保计数器的值在重建后不会丢失。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)