从后台栈中恢复片段时使用savedInstanceState

39

我可以使用savedInstanceState()方法在移除一个fragment时保存状态,然后在从返回堆栈中弹出该fragment时恢复状态吗?但是当我从返回堆栈中恢复fragment时,savedInstanceState捆绑对象始终为null。

目前,应用程序流程如下:fragment创建-> fragment删除(添加到返回堆栈)-> 从返回堆栈中恢复fragment(savedInstanceState捆绑对象为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个回答

8

5

我喜欢将onCreateView中返回的View作为全局变量存储,这样当我返回时只需要检查它即可:

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

7
不确定这是否是一个好主意。如果你保留对它的引用,这是否会违背清除视图以释放内存的目的? - craigrs84
我其实不确定,因为我没有运行任何直接测试。然而,我的想法是这样的。当您初始化布局中的所有元素时,通常将大多数元素设置为全局变量,因此如果在上面的示例中由于引用而无法回收基本视图,则Android也无法回收这些视图中的任何一个,从而导致内存出现相同的问题。 - AllDayAmazing
2
如果您需要为不同的方向充气不同的视图,则此方法无法正常工作。 - bcorso
1
这个解决方案救了我的命。 - brainmurphy1

3

问题在于片段需要与IdTag相关联,以便FragmentManager跟踪它。

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

  1. In xml layout declare an Id for your fragment:

    android:id=@+id/<Id>
    
  2. If your fragments container View has an Id, use FragmentTransaction:

    FragmentTransaction  add (int containerViewId, Fragment fragment)
    
  3. If your fragment is not associated with any View (e.g. headless fragment), give it a Tag:

    FragmentTransaction  add (Fragment fragment, String tag)
    

此外,还可以参考这个Stack Overflow的答案。


0

顺便说一下,我也遇到了这个问题,但在我的情况下,onSaveInstanceState 被正确调用,并且当智能手机上的新活动片段被带出时,我推入了我的状态数据。和你一样,onActivityCreated 始终为空。在我看来,我认为这是一个错误。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接