首页 文章

从后台堆栈恢复片段时的savedInstanceState

提问于
浏览
35

我可以在删除片段时使用 savedInstanceState() 保存状态,然后在从后端堆栈弹出片段时恢复状态吗?当我从后台堆栈恢复片段时,savedInstanceState包始终为null .

现在,app流程是:创建片段 - >删除片段(添加到后台堆栈) - >从后台堆栈恢复的片段(savedInstanceState bundle为null) .

这是相关代码:

public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle bundle = getArguments();
    Long playlistId = bundle.getLong(Constants.PLAYLIST_ID);
    int playlistItemId = bundle.getInt(Constants.PLAYLISTITEM_ID);

    if (savedInstanceState == null) {
       selectedVideoNumber = playlistItemId;
    } else {
       selectedVideoNumber = savedInstanceState.getInt("SELECTED_VIDEO");
    }
}

public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(Constants.SELECTED_VIDEO, selectedVideoNumber);
    }

我认为问题是 onSavedInstanceState() 在被删除并被添加到后台堆栈时从不被调用 . 如果我不能使用onsavedInstanceState(),还有另一种方法来解决这个问题吗?

4 回答

  • 6

    (遗憾的是)onSaveInstanceState在片段的正常后向堆栈重新创建中未被调用 . 查看http://developer.android.com/guide/components/fragments.html#CreatingHow can I maintain fragment state when added to the back stack?上的答案

  • 4

    我喜欢将我在onCreateView中返回的View作为全局变量存储,然后当我返回时,我只需检查一下:

    if(mBaseView != null) {
            // Remove the view from the parent
            ((ViewGroup)mBaseView.getParent()).removeView(mBaseView);
            // Return it
            return mBaseView;
        }
    
  • 0

    问题是片段需要与 IdTag 关联,以便 FragmentManager 跟踪它 .

    至少有3种方法可以做到这一点:

    • 在xml布局中为您的片段声明 Id
    android:id=@+id/<Id>
    
    FragmentTransaction  add (int containerViewId, Fragment fragment)
    
    • 如果你的片段没有与任何 View (例如无头片段)相关联,请给它一个 Tag
    FragmentTransaction  add (Fragment fragment, String tag)
    

    Also, see this SO answer.

  • 5

    FWIW,我也打了这个,但在我的情况下onSaveInstanceState被正确调用,当我在智能手机上启动一个新的活动片段时,我推入了我的状态数据 . 和你一样,onActivityCreated被称为w / savedInstanceState,总是为null . 恕我直言,我认为这是一个错误 .

    我通过创建一个静态MyApplication状态并将数据放在那里等同于“全局变量”来解决它...

相关问题