Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Fragment 中 add 與 replace 方法的區別淺析

編輯:關於 Android 程式設計

用 FragmentTransaction 時,它提供了 add 和 replace 兩個方法,我一直對它們的區別存有疑惑。

起初我以為:用 add 時按返回鍵會回退到上一個 Fragment,而 replace 會把被替換的那個徹底移除,所以不會回退。但事實並非如此。add 和 replace 影響的只是界面,真正控制回退的是「事務(transaction)」。

 public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag)
 Add a fragment to the activity state. This fragment may optionally also have its view
 (if Fragment.onCreateView returns non-null) into a Container view of the activity.

add 是把一個 fragment 添加到容器 container 裡。

 public abstract FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)
 Replace an existing fragment that was added to a container. This is essentially the same
 as calling remove(Fragment) for all currently added fragments that were added with the same
 containerViewId and then add(int, Fragment, String) with the same arguments given here.

replace 是先 remove 掉相同 id 的所有 fragment,再 add 當前這個。

大多數情況下兩者表現一致。因為我們通常用一个 FrameLayout 當容器,每個 Fragment 被 add 或 replace 進去時都顯示在最上層,看到的界面都一樣。但用 add 時,這個 FrameLayout 其實有兩層,多層自然比一層浪費資源,所以一般推薦用 replace。當然也有需要 add 的場景,比如做輪播圖,每張圖都是獨立 Fragment,容器需要 add 多個 Fragment 才能按邏輯輪播。

至於返回鍵,那是事務的問題,與用 add 還是 replace 無關。

2015.08.04 更新。

發現這篇博文被搜索得挺多,上面的分析是在官方文檔基礎上加上一些個人猜測,為避免誤人子弟,下面從代碼實現角度再分析一下。

FragmentManager 是抽象類,實現類是 FragmentManagerImpl,與它在同一個類文件裡;FragmentTransaction 也是抽象類,具體實現是 BackStackRecord。BackStackRecord 其實封裝了一個隊列。看 add 和 replace:

 public FragmentTransaction add(int containerViewId, Fragment fragment, String tag) {
 doAddOp(containerViewId, fragment, tag, OP_ADD);
 return this;
 }
 public FragmentTransaction replace(int containerViewId, Fragment fragment, String tag) {
 if (containerViewId == 0) {
 throw new IllegalArgumentException("Must use non-zero containerViewId");
 }
 doAddOp(containerViewId, fragment, tag, OP_REPLACE);
 return this;
 }

兩者都調用 doAddOp,把一個操作 Op 添加到隊列:

 private void doAddOp(int containerViewId, Fragment fragment, String tag, int opcmd) {
 fragment.mFragmentManager = mManager;
 if (tag != null) {
 if (fragment.mTag != null && !tag.equals(fragment.mTag)) {
 throw new IllegalStateException("Can't change tag of fragment " + fragment + ": was " + fragment.mTag + " now " + tag);
 }
 fragment.mTag = tag;
 }
 if (containerViewId != 0) {
 if (fragment.mFragmentId != 0 && fragment.mFragmentId != containerViewId) {
 throw new IllegalStateException("Can't change container ID of fragment " + fragment + ": was " + fragment.mFragmentId + " now " + containerViewId);
 }
 fragment.mContainerId = fragment.mFragmentId = containerViewId;
 }
 Op op = new Op();
 op.cmd = opcmd;
 op.fragment = fragment;
 addOp(op);
 }

run 方法才是真正執行的地方。一系列操作會一次性執行,而非一操作一執行。看 while 循環與 OP_ADD、OP_REPLACE 分支即可:

 public void run() {
 if (FragmentManagerImpl.DEBUG) {
 Log.v(TAG, "Run: " + this);
 }
 if (mAddToBackStack) {
 if (mIndex < 0) {
 throw new IllegalStateException("addToBackStack() called after commit()");
 }
 }
 bumpBackStackNesting(1);
 SparseArray<Fragment> firstOutFragments = new SparseArray<Fragment>();
 SparseArray<Fragment> lastInFragments = new SparseArray<Fragment>();
 calculateFragments(firstOutFragments, lastInFragments);
 beginTransition(firstOutFragments, lastInFragments, false);
 // 獲取隊列的頭
 Op op = mHead;
 while (op != null) {
 switch (op.cmd) {
 case OP_ADD: {
 Fragment f = op.fragment;
 f.mNextAnim = op.enterAnim;
 mManager.addFragment(f, false);//添加
 } break;
 case OP_REPLACE: {
 Fragment f = op.fragment;
 if (mManager.mAdded != null) {
 for (int i = 0; i < mManager.mAdded.size(); i++) {
 Fragment old = mManager.mAdded.get(i);
 if (f == null || old.mContainerId == f.mContainerId) {
 if (old == f) {
 op.fragment = f = null;
 } else {
 if (op.removed == null) {
 op.removed = new ArrayList<Fragment>();
 }
 op.removed.add(old);
 old.mNextAnim = op.exitAnim;
 if (mAddToBackStack) {
 old.mBackStackNesting += 1;
 }
 mManager.removeFragment(old, mTransition, mTransitionStyle);//刪除
 }
 }
 }
 }
 if (f != null) {
 f.mNextAnim = op.enterAnim;
 mManager.addFragment(f, false);//添加
 }
 } break;
 case OP_REMOVE: {
 Fragment f = op.fragment;
 f.mNextAnim = op.exitAnim;
 mManager.removeFragment(f, mTransition, mTransitionStyle);
 } break;
 case OP_HIDE: {
 Fragment f = op.fragment;
 f.mNextAnim = op.exitAnim;
 mManager.hideFragment(f, mTransition, mTransitionStyle);
 } break;
 case OP_SHOW: {
 Fragment f = op.fragment;
 f.mNextAnim = op.enterAnim;
 mManager.showFragment(f, mTransition, mTransitionStyle);
 } break;
 case OP_DETACH: {
 Fragment f = op.fragment;
 f.mNextAnim = op.exitAnim;
 mManager.detachFragment(f, mTransition, mTransitionStyle);
 } break;
 case OP_ATTACH: {
 Fragment f = op.fragment;
 f.mNextAnim = op.enterAnim;
 mManager.attachFragment(f, mTransition, mTransitionStyle);
 } break;
 default: {
 throw new IllegalArgumentException("Unknown cmd: " + op.cmd);
 }
 }
 op = op.next;//隊列的下一個
 }
 mManager.moveToState(mManager.mCurState, mTransition, mTransitionStyle, true);
 if (mAddToBackStack) {
 mManager.addBackStackState(this);
 }
 }

BackStackRecord 構造器裡有 FragmentManager 參數,所以它持有 FragmentManager 引用,可直接調用其 addFragment 方法。每次 add 一個 Fragment,都會被放進 mAdded 容器:

 public void addFragment(Fragment fragment, boolean moveToStateNow) {
 if (mAdded == null) {
 mAdded = new ArrayList<Fragment>();
 }
 if (DEBUG) Log.v(TAG, "add: " + fragment);
 makeActive(fragment);
 if (!fragment.mDetached) {
 if (mAdded.contains(fragment)) {
 throw new IllegalStateException("Fragment already added: " + fragment);
 }
 mAdded.add(fragment);
 fragment.mAdded = true;
 fragment.mRemoving = false;
 if (fragment.mHasMenu && fragment.mMenuVisible) {
 mNeedMenuInvalidate = true;
 }
 if (moveToStateNow) {
 moveToState(fragment);
 }
 }
 }

有時你 add Fragment A,再 add Fragment B,B 把 A 蓋住了,點菜單時 A 和 B 的選項卻都出來了——為什麼?因為創建 OptionsMenu 時,FragmentManager 遍歷了 mAdded,所以兩者的菜單都被加了進來。也就是說,用 add 時,即便 B 蓋住了 A,A 依然存活且活躍:

 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
 boolean show = false;
 ArrayList<Fragment> newMenus = null;
 if (mAdded != null) {
 for (int i=0; i<mAdded.size(); i++) {
 Fragment f = mAdded.get(i);
 if (f != null) {
 if (f.performCreateOptionsMenu(menu, inflater)) {
 show = true;
 if (newMenus == null) {
 newMenus = new ArrayList<Fragment>();
 }
 newMenus.add(f);
 }
 }
 }
 }
 if (mCreatedMenus != null) {
 for (int i=0; i<mCreatedMenus.size(); i++) {
 Fragment f = mCreatedMenus.get(i);
 if (newMenus == null || !newMenus.contains(f)) {
 f.onDestroyOptionsMenu();
 }
 }
 }
 mCreatedMenus = newMenus;
 return show;
 }

小結

使用 add 方法時,要留意 fragment 引用被清空的情況。add 到 activity 的 fragment 對象並不會被銷毀,只是 view 被置為 null,此時若重新賦值,hide 和 show 都不會生效;一個 activity 有多個 fragment 時,很可能出現層疊而無法正常顯示或隱藏。

add 的優點是佔用內存少;replace 雖佔用資源稍多,卻沒有 add 的這些 bug。所以開發時盡量處理好 add 可能引起的问题。此外,fragment 還要妥善處理 commit 與 commitAllowingStateLoss() 兩個方法。

以上就是 add 與 replace 區別的淺析,希望對大家有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved