I. Differences between remvoefragment and detachfragment:
public void removeFragment(Fragment fragment, int transition, int transitionStyle) { if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); final boolean inactive = !fragment.isInBackStack(); if (!fragment.mDetached || inactive) { if (mAdded != null) { mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; fragment.mRemoving = true; moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED, transition, transitionStyle, false); } }
For fragment not added to the rollback stack, removeframent will move the fragmentInitializingStatus. You can view the movetostate method. This fragment will beMakeinactive, Remove from the madded and mactive lists, and finally execute the ondestroy and ondetach lifecycle methods. PS: executed in the addfragment MethodMakeactive
public void detachFragment(Fragment fragment, int transition, int transitionStyle) { if (DEBUG) Log.v(TAG, "detach: " + fragment); if (!fragment.mDetached) { fragment.mDetached = true; if (fragment.mAdded) { // We are not already in back stack, so need to remove the fragment. if (mAdded != null) { if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; moveToState(fragment, Fragment.CREATED, transition, transitionStyle, false); } } }
Detachfragment moves the fragment from the current State (possibly resumed)CreatedStatus, fragment will not be removed from the mactive list, and the lifecycle method is executed to ondestroyview.
Attachfragment will re-Add the fragment of the previous detach to the madded list and execute movetostate (... mcurstate...). The mcurstate here is the State that fragmentmanager synchronizes from the activity.
Conclusion: addfragment and removefragment are executed more thoroughly. They are a process from none to none. detachfragment and attachfragment only change the fragment state, and fragment objects will not be released, for example, if a fragment is in the resumed state (of course, its activity is also in the resumed State), it is visible. If we perform the detach operation on this fragment, it will disappear from the UI, then execute the attach operation, and its status can be restored to resumed and returned to the field of view.
2. the execution process is also different:
Addfragment first to removefragment;
Detachfragment before attachfragment.
Differences between remvoefragment and detachfragment in Fragment