【Android原始碼】Fragment 原始碼分析

指間沙似流年發表於2017-12-23

fragment官方介紹

通常情況下我們使用fragment的方式是這樣的:

FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.add(mContainerViewId, fragment);
fragmentTransaction.commit();
複製程式碼

那麼Fragment是如果建立的,如何被新增到佈局中的呢,我們一起來分析下系統是如何做的。

通過點選addbeginTransaction可以發現都是抽象方法,那麼只能通過getFragmentManager()首先獲得 FragmentManager:

public FragmentManager getFragmentManager() {
   return mFragments.getFragmentManager();
}

final FragmentManagerImpl mFragmentManager = new FragmentManagerImpl();
複製程式碼

最終可以獲得FragmentManagerImpl這個FragmentMananger實現類。

// FragmentManagerImpl.java
@Override
public FragmentTransaction beginTransaction() {
   return new BackStackRecord(this);
}

// BackStackRecord.java
public FragmentTransaction add(Fragment fragment, String tag) {
   doAddOp(0, fragment, tag, OP_ADD);
   return this;
}

public FragmentTransaction add(int containerViewId, Fragment fragment) {
   doAddOp(containerViewId, fragment, null, OP_ADD);
   return this;
}

public FragmentTransaction add(int containerViewId, Fragment fragment, String tag) {
   doAddOp(containerViewId, fragment, tag, OP_ADD);
   return this;
}
複製程式碼

最終通過呼叫BackStackRecord的doAddOp(int containerViewId, Fragment fragment, String tag, int opcmd)方法將fragment加入管理中。

private void doAddOp(int containerViewId, Fragment fragment, String tag, int opcmd) {
   fragment.mFragmentManager = mManager;

   Op op = new Op();
   op.cmd = opcmd;
   op.fragment = fragment;
   addOp(op);
}

void addOp(Op op) {
   if (mHead == null) {
       mHead = mTail = op;
   } else {
       op.prev = mTail;
       mTail.next = op;
       mTail = op;
   }
   op.enterAnim = mEnterAnim;
   op.exitAnim = mExitAnim;
   op.popEnterAnim = mPopEnterAnim;
   op.popExitAnim = mPopExitAnim;
   mNumOp++;
}
複製程式碼

可以發現在add方法中,系統只做了賦值操作,並沒有對fragment進行任何操作,所以應該是在commit中進行操作的:

// BackStackRecord.java
public int commit() {
   return commitInternal(false);
}

int commitInternal(boolean allowStateLoss) {
   if (mCommitted) {
       throw new IllegalStateException("commit already called");
   }
   if (FragmentManagerImpl.DEBUG) {
       Log.v(TAG, "Commit: " + this);
       LogWriter logw = new LogWriter(Log.VERBOSE, TAG);
       PrintWriter pw = new FastPrintWriter(logw, false, 1024);
       dump("  ", null, pw, null);
       pw.flush();
   }
   mCommitted = true;
   if (mAddToBackStack) {
       mIndex = mManager.allocBackStackIndex(this);
   } else {
       mIndex = -1;
   }
   mManager.enqueueAction(this, allowStateLoss);
   return mIndex;
}

// FragmentManager.java
public int allocBackStackIndex(BackStackRecord bse) {
   synchronized (this) {
       if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) {
           if (mBackStackIndices == null) {
               mBackStackIndices = new ArrayList<BackStackRecord>();
           }
           int index = mBackStackIndices.size();
           if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse);
           mBackStackIndices.add(bse);
           return index;

       } else {
           int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1);
           if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse);
           mBackStackIndices.set(index, bse);
           return index;
       }
   }
}

public void enqueueAction(Runnable action, boolean allowStateLoss) {
   if (!allowStateLoss) {
       checkStateLoss();
   }
   synchronized (this) {
       mPendingActions.add(action);
       if (mPendingActions.size() == 1) {
           mHost.getHandler().removeCallbacks(mExecCommit);
           mHost.getHandler().post(mExecCommit);
       }
   }
}
複製程式碼

commit方法最終呼叫了manager的allocBackStackIndexenqueueAction方法,其中allocBackStackIndex方法將BackStackRecord新增到了mBackStackIndices中,而enqueueAction方法首先將實現了Runnable的BackStackRecord新增到了mPendingActions,之後呼叫了handler。

// FragmentManagerImpl.java
Runnable mExecCommit = new Runnable() {
   @Override
   public void run() {
       execPendingActions();
   }
};

public boolean execPendingActions() {
   while (true) {
       int numActions;
       
       synchronized (this) {
           numActions = mPendingActions.size();
           if (mTmpActions == null || mTmpActions.length < numActions) {
               mTmpActions = new Runnable[numActions];
           }
           mPendingActions.toArray(mTmpActions);
           mPendingActions.clear();
           mHost.getHandler().removeCallbacks(mExecCommit);
       }
       
       mExecutingActions = true;
       for (int i=0; i<numActions; i++) {
           mTmpActions[i].run();
           mTmpActions[i] = null;
       }
       mExecutingActions = false;
       didSomething = true;
   }

   doPendingDeferredStart();

   return didSomething;
}
複製程式碼

execPendingActions方法首先將mPendingActions賦值給了mTmpActions,之後通過for迴圈呼叫run方法:

// BackStackRecord.java
public void run() {
//程式碼省略
   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;
               int containerId = f.mContainerId;
               if (mManager.mAdded != null) {
                   for (int i = mManager.mAdded.size() - 1; i >= 0; i--) {
                       Fragment old = mManager.mAdded.get(i);
                       if (FragmentManagerImpl.DEBUG) {
                           Log.v(TAG,
                                   "OP_REPLACE: adding=" + f + " old=" + old);
                       }
                       if (old.mContainerId == containerId) {
                           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;
                                   if (FragmentManagerImpl.DEBUG) {
                                       Log.v(TAG, "Bump nesting of "
                                               + old + " to " + old.mBackStackNesting);
                                   }
                               }
                               mManager.removeFragment(old, mTransition, mTransitionStyle);
                           }
                       }
                   }
               }
               if (f != null) {
                   f.mNextAnim = op.enterAnim;
                   mManager.addFragment(f, false);
               }
           }
           break;
           // 程式碼省略
       }

       op = op.next;
   }

   mManager.moveToState(mManager.mCurState, mTransition,
           mTransitionStyle, true);

   if (mAddToBackStack) {
       mManager.addBackStackState(this);
   }
}
複製程式碼

這個時候就用上了我們之前add方法的opcmd欄位,add賦值的欄位是OP_ADD,所以可以看到直接呼叫了mManager.addFragment(f, false)方法;而replace方法賦值的欄位是OP_REPLACE,首先呼叫mManager.removeFragment(old, mTransition, mTransitionStyle)方法將上一個fragment移除,之後再呼叫mManager.addFragment(f, false)

public void addFragment(Fragment fragment, boolean moveToStateNow) {
   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);
       }
   }
}

void moveToState(Fragment f) {
   moveToState(f, mCurState, 0, 0, false);
}
複製程式碼

這個時候呼叫的moveToState方法就涉及到了Fragment的生命週期:

void moveToState(Fragment f, int newState, int transit, int transitionStyle,
       boolean keepActive) {
	switch (f.mState) {
      case Fragment.INITIALIZING:
      	// fragment的onAttach方法
      	f.onAttach(mHost.getContext());
      	if (!f.mRetaining) {
      			// fragment的onCreate方法
			    f.performCreate(f.mSavedFragmentState);
			} else {
			    f.restoreChildFragmentState(f.mSavedFragmentState, true);
			    f.mState = Fragment.CREATED;
			}
			if (f.mFromLayout) {
				// fragment的onCreateView方法
				f.mView = f.performCreateView(f.getLayoutInflater(
				       f.mSavedFragmentState), null, f.mSavedFragmentState);
				if (f.mView != null) {
				   f.mView.setSaveFromParentEnabled(false);
				   if (f.mHidden) f.mView.setVisibility(View.GONE);
				   // fragment的onViewCreated方法
				   f.onViewCreated(f.mView, f.mSavedFragmentState);
				}
			}
			//程式碼省略
}	
複製程式碼

相關文章