duc*_*kgo 8 android android-fragments
我对操作系统的配置更改处理有疑问,假设我在其 onCreate() 中有一个 Activity,它正在使用该片段中定义的特殊构造函数创建一个(或多个)片段实例。
当设备方向更改时,系统将再次销毁并创建片段,如果我是正确的,它将使用默认(无参数)构造函数来执行此操作,同时活动也会重新创建,并且它将再次使用相同的构造函数实例化片段。我的问题是,内存中会存在两个不同的实例吗?如果不是,如何解决并合而为一?
在活动的整个生命周期中保持片段状态的责任在于,这就是为什么在提交片段事务时FragmentManager可以选择 tocommit和 to 。commitAllowingStateLoss如果留给它自己的设备,其Fragment状态将自动恢复。但是...如果您在代码中添加片段(而不是在 xml 布局中添加它),那么您就可以仅在需要时添加它。
通常,在这种情况下,onCreate检查 Activity 是否未重新启动就足够了,即检查savedInstanceState == null并仅添加片段。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
}
你的问题的答案:
内存中会存在两个不同的实例吗?
是的,如果您只是在每次调用时添加片段,onCreate就会有多个实例。
| 归档时间: |
|
| 查看次数: |
5210 次 |
| 最近记录: |