使用的onSaveInstanceState在backstack片段? [英] Using onSaveInstanceState with fragments in backstack?

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

问题描述

我有我的碎片保持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 在<$ C存在了$ C>活动是死于与所有的片段。

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.

由于<一个href="http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState%28android.os.Bundle%29"相对=nofollow>文档说:

有很多情况下,一个片段可能大多是拆掉了,但它的状态不会被保存,直到其所属活动实际上需要保存其状态(当放在后面堆栈没有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! :-)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆