本文介绍了将 onSaveInstanceState 与 backstack 中的片段一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将片段保存在 FragmentManager 的后台堆栈中.每个片段状态都保存为使用成员变量进行方向更改,例如:

I have fragments I keep in the backstack of FragmentManager. Every fragment state is saved for orientation changes with member variables, like this for example:

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putLong("userId", mUserId);
    outState.putString("username", mUsername);
}

我的问题是,如果有一个方向改变,因为 backstack 中的每个片段都是通过 onSaveInstanceState 调用的,我得到一个空指针异常,因为成员变量不再存在.

My problem is that if there is an orientation change, since every fragment in the backstack gets called via onSaveInstanceState, I get a null pointer exception because the member variables don't exist anymore.

关于如何解决这个问题的任何想法?

Any ideas on how to solve this?

推荐答案

可能你的成员变量不存在了,因为你的 Activity 中的 FragmentManager 是带着你所有的碎片死去.

It is possible that your member variables don't exist anymore because the FragmentManager in your Activity is dying with all of your fragments.

您还需要覆盖 Activity 类的方法 onSaveInstanceState,因为您需要在保存之前保存 Activity 状态Fragments 状态.

You need to override the method onSaveInstanceState of your Activity class as well, because you need to save the Activity state before you save the Fragments state.

作为文档 说:

在很多情况下,一个片段可能大部分被拆除(例如当放置在没有 UI 显示的后端堆栈上时),但它的状态不会被保存,直到其拥有的 Activity 实际需要保存其状态.

更新

在你的 Activity onSaveInstanceStateonRestoreInstanceState 中,尝试保存你的 Fragment 引用,然后用类似的东西恢复它们这个:

In your Activity onSaveInstanceState and onRestoreInstanceState, try saving you Fragment references and then restore them with something like this:

public void onSaveInstanceState(Bundle outState){
    getFragmentManager().putFragment(outState, "myfragment", myfragment);
}
public void onRestoreInstanceState(Bundle inState){
    myFragment = getFragmentManager().getFragment(inState, "myfragment");
}

然后告诉我你是否幸运!:-)

Tell me then if you had luck! :-)

这篇关于将 onSaveInstanceState 与 backstack 中的片段一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:48
查看更多