Fragments - kgleong/software-engineering GitHub Wiki

Fragment Lifecycle

When is onSaveInstanceState called?

Fragment#onSaveInstanceState() is called whenever Activity#onSaveInstanceState() is called.

Here's a look at the call chain:

In FragmentActivity, which is the support library base activity class:

  • any call to onSaveInstanceState() triggers a call to the activity's fragment manager to save the state for all of the fragments in this activity.
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // mFragments is the fragment manager for this activity
        // saveAllState() saves the state for all fragments in this activity.
        Parcelable p = mFragments.saveAllState();
        if (p != null) {
            outState.putParcelable(FRAGMENTS_TAG, p);
        }
    }

In FragmentManagerImpl, which is the concrete FragmentManager class that manages fragments for all FragmentActivity instances:

  • It's important to note that every fragment manager has a mActive field that is of type ArrayList<Fragment>.
    • This is a list of all fragments in the associated activity. A fragment manager is associated with only a single activity.
    Parcelable saveAllState() {
        ...
        // mActive is a list of all fragments in this activity.
        for (int i = 0; i < mActive.size(); i++) {
            Fragment f = mActive.get(i);
            if (f != null) {
                ...
                // This constructor never sets mSavedFragmentState.
                FragmentState fs = new FragmentState(f);
                ...
                // All fragments start in the INITIALIZING state and don't stay
                // here for very long unless they're about to be detached/destroyed
                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
           
                    // saveFragmentBasicState() calls f.onSaveInstanceState()
                    fs.mSavedFragmentState = saveFragmentBasicState(f);
                ...
                }
            }
        }
        ...
    }

    Bundle saveFragmentBasicState(Fragment f) {
        ...
        // This is what calls fragment#onSaveInstanceState()
        f.performSaveInstanceState(mStateBundle);
        ...
    }
⚠️ **GitHub.com Fallback** ⚠️