【问题标题】:Are fragments saved by default with savedInstanceState?默认情况下是否使用 savedInstanceState 保存片段?
【发布时间】:2014-08-19 18:16:41
【问题描述】:

我阅读了What's onCreate(Bundle savedInstanceState) onsaveinstancestate 为您提供了应用程序先前状态的捆绑包(如果屏幕的方向发生了变化。

我查看了 Android 文档 (http://developer.android.com/training/basics/activity-lifecycle/recreating.html),发现您必须手动将要保存的值保存为键值对。他们这样做的代码是

    static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

我的问题是片段,当方向改变和重新创建活动时,它们会自动重新附加吗?您是否必须输入代码才能将其保存到包中? 这是我试图理解的这种情况的 Facebook 代码

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (savedInstanceState == null) {
    // Add the fragment on initial activity setup
    mainFragment = new MainFragment();
    getSupportFragmentManager()
    .beginTransaction()
    .add(android.R.id.content, mainFragment)
    .commit();
} else {
    // Or set the fragment from restored state info
    mainFragment = (MainFragment) getSupportFragmentManager()
    .findFragmentById(android.R.id.content);
}

}

【问题讨论】:

    标签: android facebook android-fragments


    【解决方案1】:

    要在 Activity 被销毁时保留片段,以便它自动重新连接,您应该调用

    Fragment.setRetainInstance(true)
    

    在 Fragment 的构造函数中。 onSaveInstanceState()默认不保存任何内容

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多