How to correctly save instance state of Fragments in back stack?

后端 未结 6 1287
小鲜肉
小鲜肉 2020-11-21 11:57

I have found many instances of a similar question on SO but no answer unfortunately meets my requirements.

I have different layouts for portrait and landscape and I

6条回答
  •  梦如初夏
    2020-11-21 12:09

    To correctly save the instance state of Fragment you should do the following:

    1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

    class MyFragment extends Fragment {
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            ...
            if (savedInstanceState != null) {
                //Restore the fragment's state here
            }
        }
        ...
        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
    
            //Save the fragment's state here
        }
    
    }
    

    2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

    class MyActivity extends Activity {
    
        private MyFragment 
    
        public void onCreate(Bundle savedInstanceState) {
            ...
            if (savedInstanceState != null) {
                //Restore the fragment's instance
                mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
                ...
            }
            ...
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
    
            //Save the fragment's instance
            getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
        }
    
    }
    

    Hope this helps.

提交回复
热议问题