hee*_*ero 36 android bundle android-fragments 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);
}
Run Code Online (Sandbox Code Playgroud)
我认为问题是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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55324 次 |
| 最近记录: |