为什么有必要在OnCreate中检查savedInstanceState?

时间:2015-07-07 19:47:32

标签: android oncreate

onCreate()方法中if块的用途是什么?为什么有必要检查savedInstanceState是否为空?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

2 个答案:

答案 0 :(得分:3)

重新创建活动时,例如在屏幕旋转或其他configuration change之后,会自动重新附加片段。通过检查是否savedInstanceState == null,您可以确保不会重新添加已为您添加的片段。

答案 1 :(得分:0)

那么这样你就可以记住他们上次离开你的应用时的位置。因此,例如chrome会记住您上次访问过的标签页。