我对 os 的配置更改处理有疑问,假设我在其 onCreate() 中有一个 Activity ,它正在使用该 fragment 中定义的特殊构造函数创建一个(或多个) fragment 实例。
当设备方向改变时,系统将销毁并再次创建 fragment ,如果我是正确的,它将使用默认(无参数)构造函数来执行此操作,同时 Activity 也将被重新创建,它将再次使用相同的构造函数实例化 fragment 。我的问题是,内存中会不会有两个不同的实例?如果不是,它们如何解决并成为一个?
最佳答案
一些背景
在 Activity 的整个生命周期中保持 fragment 状态的责任在 FragmentManager
上,这就是为什么有一个选项 commit
和 commitAllowingStateLoss
提交 fragment 事务时。如果留给它自己的设备,Fragment
的状态将自动恢复。但是...如果您在代码中添加 fragment (而不是在 xml 布局中添加),那么您只能在需要时添加它。
通常,在 onCreate
的情况下,检查 Activity 是否未重新启动就足够了,也就是说,检查 savedInstanceState == null
然后才添加 fragment 。
看看 fragment 指南中的这个 fragment :
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
附言
问题的答案:
will there be two different instances in the memory?
是的,如果您只是在每次调用 onCreate
时添加 fragment ,就会有多个实例。
关于android - 配置更改时的 fragment 重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855464/