savedInstanceState when restoring fragment from back stack

梦想与她 提交于 2019-12-02 18:48:10
Eric

onSaveInstanceState is (unfortunately) not called in normal back-stack re-creation of a fragment. Check out http://developer.android.com/guide/components/fragments.html#Creating and the answer on How can I maintain fragment state when added to the back stack?

I like to store the View I return in onCreateView as a global variable and then when I return I simply check this:

if(mBaseView != null) {
        // Remove the view from the parent
        ((ViewGroup)mBaseView.getParent()).removeView(mBaseView);
        // Return it
        return mBaseView;
    }
bcorso

The problem is that the fragment needs to have an Id or Tag associated with it in order for the FragmentManager to keep track of it.

There are at least 3 ways to do this:

  1. In xml layout declare an Id for your fragment:

    android:id=@+id/<Id>
    
  2. If your fragments container View has an Id, use FragmentTransaction:

    FragmentTransaction  add (int containerViewId, Fragment fragment)
    
  3. If your fragment is not associated with any View (e.g. headless fragment), give it a Tag:

    FragmentTransaction  add (Fragment fragment, String tag)
    

Also, see this SO answer.

FWIW, I hit this as well, but in my case onSaveInstanceState was called properly and I pushed in my state data when a new activity fragment was brought up on the smartphone. Same as you, the onActivityCreated was called w/ savedInstanceState always null. IMHO, I think it's a bug.

I worked around it by creating a static MyApplication state and putting the data there for the equivalent of "global variables"...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!