[英]savedInstanceState when restoring fragment from back stack
我可以使用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(),还有另一种方法可以解决这个问题吗?
(遗憾的是)onSaveInstanceState在片段的正常后向堆栈重新创建中未被调用。 查看http://developer.android.com/guide/components/fragments.html#Creating以及如何在添加到后台堆栈时如何维护片段状态?
我喜欢将我在onCreateView中返回的View作为全局变量存储,然后当我返回时,我只需检查一下:
if(mBaseView != null) {
// Remove the view from the parent
((ViewGroup)mBaseView.getParent()).removeView(mBaseView);
// Return it
return mBaseView;
}
问题是片段需要有一个Id
或Tag
与之关联,以便FragmentManager
跟踪它。
至少有3种方法可以做到这一点:
在xml布局中声明片段的Id
:
android:id=@+id/<Id>
如果您的片段容器View
具有Id
,请使用FragmentTransaction :
FragmentTransaction add (int containerViewId, Fragment fragment)
如果您的片段与任何View
(例如无头片段)无关,请为其指定Tag
:
FragmentTransaction add (Fragment fragment, String tag)
FWIW,我也打了这个,但在我的情况下onSaveInstanceState被正确调用,当我在智能手机上启动一个新的活动片段时,我推入了我的状态数据。 和你一样,onActivityCreated被称为w / savedInstanceState,总是为null。 恕我直言,我认为这是一个错误。
我通过创建一个静态MyApplication状态并将数据放在那里等同于“全局变量”来解决它...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.