[英]Why do you check for savedInstanceState == null when adding fragment?
在片段doc中 ,在其中一个示例中,他们在添加片段时检查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();
}
}
}
这项检查的目的是什么? 如果它不存在会发生什么?
这项检查的目的是什么?
不要将片段添加两次,但我更喜欢检查片段是否在那里,而不是依赖于Bundle
为null
。
如果它不存在会发生什么?
最初,没有,因为Bundle
在首次创建活动时将为null
。
然而,然后,用户将设备的屏幕从纵向旋转到横向。 或者,用户更改语言。 或者,用户将设备放入制造商提供的汽车底座中。 或者,用户进行任何其他配置更改。
默认情况下,您的活动将被销毁并重新创建。 默认情况下,您的片段也将被销毁并重新创建(例外:调用setRetainInstance(true)
片段,这些片段与旧活动分离并附加到新活动)。
因此, 第二次创建活动 - 由于配置更改而创建的实例 - 您的片段已经存在 ,因为它已重新创建或保留。 您不希望该片段的第二个实例(通常),因此您会采取措施来检测是否已发生这种情况,并且不会运行新的FragmentTransaction
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.