android - 无法保存和恢复嵌套 fragment ?

标签 android android-fragments android-orientation android-nested-fragment

我有一个嵌套的 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/

相关文章:

android - Android 上的 "Enable Library Loading"开发者选项在哪里?

Android DrawerLayout - 让 child 获得焦点

android - 更改方向时更改 RecyclerView 的布局

android - 当我在 MotionLayout 中使用 RecyclerView 和 SwipeRefreshLayout 做一些动画时,事情变得很奇怪

java - TreeMap 自动删除自身

android - 为什么我可以通过 Bundle 传递带有位图的可序列化对象,但当系统尝试序列化它时却出现错误?

Android fragment 布局帮助

android - 自定义属性 - 方向变化

android - 我的观点正在因方向改变而被重置

android - adb: 无法打开 app.apk: 不允许操作