一, remvoeFragment 和 detachFragment 的區別:java
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); } }
對於沒有加到回退棧的fragment, removeFrament 會把該fragment 移到 INITIALIZING 狀態 , 查看 moveToState 方法能夠知道,該fragment 會被makeInactive,從mAdded 和 mActive 列表移除, 並最終執行onDestroy 、onDetach生命週期方法。ps:在addFragment方法中執行了makeActivespa
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 會把fragment 從當前狀態(多是Resumed)移動到 CREATED 狀態, fragment不會從mActive 列表移除, 生命週期方法執行到 onDestroyView。code
attachFragment 會把以前detach的fragment從新加入mAdded列表,並執行 moveToState(.. mCurState ..) , 這裏的mCurState 是fragmentManager從 Activity同步過來的狀態。對象
總結: addFragment 和 removeFragment 執行的更完全,是從 無-有-無 的過程 , 而detachFragment和attachFragment只是改變了fragment的狀態,fragment對象不會被釋放掉,好比一個fragment當前是resumed狀態(固然它所在的activity也是resumed狀態), 是可見的,咱們對這個fragment執行detach操做,那麼它會從UI中消失,而後執行attach操做,它的狀態還能夠恢復到resumed, 又回到視野中。生命週期
二,執行的過程也有不一樣:rem
先 addFragment 才能 removeFragment;同步
先 detachFragment 才能 attachFragment。it