我正在研究片段,我在文档主题详细信息示例中检查了文档here中的教程。我们有两个片段,一个用于文章标题,选择时会显示详细的文章视图(多窗格布局)。除了一小部分之外,我得到了大部分教程,为什么他们检查onCreate方法中的savedInstancestate。
所以我的问题是关于容器活动的onCreate()方法。它有这个检查
if (savedInstanceState != null) {
return;
}
当我删除它时,片段在ui中重叠。所以我知道它阻止了这个,但我不知道为什么?我希望有人向我解释一下。
提前致谢。
编辑:完整的方法
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
答案 0 :(得分:4)
我明白了。
重点是:如果活动被屏幕旋转行为破坏,活动包含的片段会自动保存。
因此,当活动从先前状态(屏幕旋转)恢复时,再次调用onCreate()方法,这意味着当屏幕旋转时将再次添加片段(根据上面的代码)。所以我们必须在onCreate()方法中检查是否从旋转if (savedInstanceState != null)
恢复,所以不需要重新添加片段,只是什么也不做。
答案 1 :(得分:3)
savedInstanceState检查上次保存的状态。
在Android中,无论何时旋转设备或从另一个Activity返回,Android的一般生命周期都应该开始,例如onCreate> onStart> onResume等等。 这意味着您的整个活动都是从新鲜事业开始的。
但是在savedInstanceState中,您将获得您已保存或正在使用的UI的最后状态。