我有一个嵌套的 Fragment,我试图在给定方向更改的情况下恢复状态。
首先我的设置如下:
Activity -> ParentFragment (SetRetainInstance(true)) -> ChildFragment
在 My Child fragment 中,我有如下的 onSaveInstance 代码:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActivity().getActionBar()
.getSelectedNavigationIndex());
}
但是,当我在所有 LifeCycle 事件中定位设备时,返回的 savedInstance 状态为 null。
我是否为 ChildFragment 做错了?为什么我的状态没有被保存和返回?
最佳答案
这是由于您的父 fragment 的 setRetainInstance(true)
造成的。 Android 保留一个 fragment 及其所有子 fragment 。所以你的 ChildFragment 没有被破坏,这就是你在 savedInstanceState 中得到 null 的原因。 onCreateView 的文档状态:
savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.
您可以尝试注释掉 setRetainInstance(true)
并确保您获得正确的 savedInstanceState 值。
关于android - 无法保存和恢复嵌套 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25913187/