使用的onSaveInstanceState在backstack片段?片段、onSaveInstanceState、backstack

2023-09-12 02:15:27 作者:[伤我者亡]

我有我的碎片保持FragmentManager的backstack。每一个片段状态保存与成员变量的方向变化,像这样的例子:

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?

推荐答案

这可能是你的成员变量千万不要因为 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.

您需要覆盖的方法的onSaveInstanceState 活动类为好,因为你需要保存活动状态保存片段前状态。

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表现,如)。

There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

更新

在你的活动 的onSaveInstanceState onRestoreInstanceState ,尝试节省您的片段引用,然后恢复他们的东西是这样的:

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! :-)