Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between mAdded & mActive in source code of support.FragmentManager

Recently I'm reading the source code of FragmentActivity(sorry that I can't find the source in github, I'm using a native source jar file). The FragmentManager contains the following two members:

ArrayList<Fragment> mAdded; //
ArrayList<Fragment> mActive; //

What's the difference of the two? and in what cases a Fragment will be in mAdded while not in mActive?

like image 821
suitianshi Avatar asked Mar 19 '23 13:03

suitianshi


1 Answers

mAdded:

  • Contains fragments that have been added and not removed or detached from the activity.
  • These fragments are privileged in the sense that they can:
    • Respond to events such as:
      • low memory events
      • configuration changes
    • Display custom menus and respond to menu item selections.

mActive:

  • A superset of mAdded that includes all fragments referenced by any FragmentTransaction objects in the backstack.
  • Fragments that are NOT in mAdded will not be able to respond to events or display custom menus.

What events modify these two fragment lists?

  • mAdded

    • a fragment is added to this list if the fragment is added to the activity.
    • a fragment is removed from this list if:
      • the fragment is removed from the activity.
      • the fragment is detached from the activity.
  • mActive

    • a fragment is added to this list if the fragment is added to the activity.
    • a fragment is removed from this list ONLY under the following two scenarios:
      • it has been removed from the activity and is NOT in the backstack.
      • a transaction is popped off the backstack and either an add or replace operation is reversed on a fragment that is now no longer referenced by the backstack.

Conclusion

mAdded is a list of fragments that the are alive in a sense, while the mActive list is a complete list of all fragments that are still tied to the activity. mActive contains all living fragments (mAdded) and freeze dried fragments (sitting on the backstack waiting to be resuscitated via backStackRecord.popFromBackStack().

Continuing with the analogy of living and cryogenically preserved entities: as activities execute callbacks like onConfigurationChanged() or onLowMemory(), the only fragments that really care about being passed the opportunity to respond to these events are the live ones.

So you'll see in FragmentManagerImpl that the callback is only looking at the mAdded or living fragments.

fragmentManager.dispatchLowMemory() is called by activity.onLowMemory().

public void dispatchLowMemory() {
    if (mAdded != null) {
        for (int i=0; i<mAdded.size(); i++) {
            Fragment f = mAdded.get(i);
            if (f != null) {
                f.performLowMemory();
            }
        }
    }
}
like image 60
orangemako Avatar answered Mar 29 '23 22:03

orangemako