从源码角度看 Fragment 生命周期(一)

1.Fragment想必是经常使用的,其存在的意义总结为:

1.1 Fragment是Activity界面的一部分,Fragment是依附于Activity之上的;
1.2 Activity是Fragment的基础,Fragment是Activity的延续和发展
1.3 一个Activity可以有多个Fragment,一个Fragment也可以被多个Activity重复使用;
1.4 一个Fragment除了Activity处于onResume状态下,他可以自己灵活的控制自己的生命周期,其他状态下,其生命周期都是由Activity所决定的;
1.5 Fragment的出现增强了UI界面布局的灵活性,可以实现动态的改变UI布局;

以上不是今天的重点,今天跟大家从源码的角度聊一聊Fragment

2.绕不开的生命周期

fragment_lifecycle.png

2.1既然Fragment 是Activity界面的一部分,就肯定绕不开Activity
当FragmentActivity在创建调用onCreate方法中

public class FragmentActivity extends ComponentActivity implements
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator {

   @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        //FragmentController是Fragment的主要控制器,分发事件
        mFragments.dispatchCreate();
    }
}
public class FragmentController {

    public void dispatchCreate() {
        //FragmentManager mFragmentManager  管理类继续分发事件 
        mHost.mFragmentManager.dispatchCreate();
    }

}
public abstract class FragmentManager implements FragmentResultOwner {

    void dispatchCreate() {
        mStateSaved = false;
        mStopped = false;
        mNonConfig.setIsStateSaved(false);
        //进入状态递推阶段
        dispatchStateChange(Fragment.CREATED);
    }

  private void dispatchStateChange(int nextState) {
        try {
            mExecutingActions = true;
            mFragmentStore.dispatchStateChange(nextState);
            //移动状态处理
            moveToState(nextState, false);
            if (USE_STATE_MANAGER) {
                Set controllers = collectAllSpecialEffectsController();
                for (SpecialEffectsController controller : controllers) {
                    controller.forceCompleteAllOperations();
                }
            }
        } finally {
            mExecutingActions = false;
        }
        execPendingActions(true);
    }


    void moveToState(int newState, boolean always) {
        if (mHost == null && newState != Fragment.INITIALIZING) {
            throw new IllegalStateException("No activity");
        }
        if (!always && newState == mCurState) {
            return;
        }
        mCurState = newState;
        if (USE_STATE_MANAGER) {
            mFragmentStore.moveToExpectedState();
        } else {
            // Must add them in the proper order. mActive fragments may be out of order
            for (Fragment f : mFragmentStore.getFragments()) {
                //遍历所有的被add 的fragment全部状态移动
                moveFragmentToExpectedState(f);
            }
            // Now iterate through all active fragments. These will include those that are removed
            // and detached.
            for (FragmentStateManager fragmentStateManager :
                    mFragmentStore.getActiveFragmentStateManagers()) {
                Fragment f = fragmentStateManager.getFragment();
                if (!f.mIsNewlyAdded) {
                    moveFragmentToExpectedState(f);
                }
                boolean beingRemoved = f.mRemoving && !f.isInBackStack();
                if (beingRemoved) {
                    mFragmentStore.makeInactive(fragmentStateManager);
                }
            }
        }
        startPendingDeferredFragments();
        if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) {
            mHost.onSupportInvalidateOptionsMenu();
            mNeedMenuInvalidate = false;
        }
    }

   void moveFragmentToExpectedState(@NonNull Fragment f) {
        if (!mFragmentStore.containsActiveFragment(f.mWho)) {
            if (isLoggingEnabled(Log.DEBUG)) {
                Log.d(TAG, "Ignoring moving " + f + " to state " + mCurState
                        + "since it is not added to " + this);
            }
            return;
        }
        //真正发起状态递推的核心方法
        moveToState(f);
        if (f.mView != null) {
            if (f.mIsNewlyAdded && f.mContainer != null) {
                // Make it visible and run the animations
                if (f.mPostponedAlpha > 0f) {
                    f.mView.setAlpha(f.mPostponedAlpha);
                }
                f.mPostponedAlpha = 0f;
                f.mIsNewlyAdded = false;
                // run animations:
                FragmentAnim.AnimationOrAnimator anim = FragmentAnim.loadAnimation(
                        mHost.getContext(), f, true, f.getPopDirection());
                if (anim != null) {
                    if (anim.animation != null) {
                        f.mView.startAnimation(anim.animation);
                    } else {
                        anim.animator.setTarget(f.mView);
                        anim.animator.start();
                    }
                }
            }
        }
        if (f.mHiddenChanged) {
            completeShowHideFragment(f);
        }
    }

   void moveToState(@NonNull Fragment f) {
        moveToState(f, mCurState);
    }
 
 void moveToState(@NonNull Fragment f, int newState) {
        FragmentStateManager fragmentStateManager =   mFragmentStore.getFragmentStateManager(f.mWho);
        if (fragmentStateManager == null) {
            fragmentStateManager = new FragmentStateManager(mLifecycleCallbacksDispatcher,
                    mFragmentStore, f);
            fragmentStateManager.setFragmentManagerState(Fragment.CREATED);
        }
        if (f.mFromLayout && f.mInLayout && f.mState == Fragment.VIEW_CREATED) {
            newState = Math.max(newState, Fragment.VIEW_CREATED);
        }
        newState = Math.min(newState, fragmentStateManager.computeExpectedState());
        if (f.mState <= newState) {//生命周期状态正推
            if (f.mState < newState && !mExitAnimationCancellationSignals.isEmpty()) {
                cancelExitAnimation(f);
            }
            switch (f.mState) {
                case Fragment.INITIALIZING:
                    if (newState > Fragment.INITIALIZING) {
                        fragmentStateManager.attach();
                    }
                    // fall through
                case Fragment.ATTACHED:
                    if (newState > Fragment.ATTACHED) {
                        fragmentStateManager.create();
                    }
                    // fall through
                case Fragment.CREATED:
                    if (newState > Fragment.INITIALIZING) {
                        fragmentStateManager.ensureInflatedView();
                    }

                    if (newState > Fragment.CREATED) {
                        fragmentStateManager.createView();
                    }
                    // fall through
                case Fragment.VIEW_CREATED:
                    if (newState > Fragment.VIEW_CREATED) {
                        fragmentStateManager.activityCreated();
                    }
                    // fall through
                case Fragment.ACTIVITY_CREATED:
                    if (newState > Fragment.ACTIVITY_CREATED) {
                        fragmentStateManager.start();
                    }
                    // fall through
                case Fragment.STARTED:
                    if (newState > Fragment.STARTED) {
                        fragmentStateManager.resume();
                    }
            }
        } else if (f.mState > newState) {//生命周期状态反推
            switch (f.mState) {
                case Fragment.RESUMED:
                    if (newState < Fragment.RESUMED) {
                        fragmentStateManager.pause();
                    }
                    // fall through
                case Fragment.STARTED:
                    if (newState < Fragment.STARTED) {
                        fragmentStateManager.stop();
                    }
                    // fall through
                case Fragment.ACTIVITY_CREATED:
                    if (newState < Fragment.ACTIVITY_CREATED) {
                        if (isLoggingEnabled(Log.DEBUG)) {
                            Log.d(TAG, "movefrom ACTIVITY_CREATED: " + f);
                        }
                        if (f.mView != null) {
                            // Need to save the current view state if not
                            // done already.
                            if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) {
                                fragmentStateManager.saveViewState();
                            }
                        }
                    }
                    // fall through
                case Fragment.VIEW_CREATED:
                    if (newState < Fragment.VIEW_CREATED) {
                        FragmentAnim.AnimationOrAnimator anim = null;
                        if (f.mView != null && f.mContainer != null) {
                            // Stop any current animations:
                            f.mContainer.endViewTransition(f.mView);
                            f.mView.clearAnimation();
                            if (!f.isRemovingParent()) {
                                if (mCurState > Fragment.INITIALIZING && !mDestroyed
                                        && f.mView.getVisibility() == View.VISIBLE
                                        && f.mPostponedAlpha >= 0) {
                                    anim = FragmentAnim.loadAnimation(mHost.getContext(),
                                            f, false, f.getPopDirection());
                                }
                                f.mPostponedAlpha = 0;
                                ViewGroup container = f.mContainer;
                                View view = f.mView;
                                if (anim != null) {
                                    FragmentAnim.animateRemoveFragment(f, anim,
                                            mFragmentTransitionCallback);
                                }
                                container.removeView(view);
                                if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
                                    Log.v(FragmentManager.TAG, "Removing view " + view + " for "
                                            + "fragment " + f + " from container " + container);
                                }
                                if (container != f.mContainer) {
                                    return;
                                }
                            }
                        }
                        if (mExitAnimationCancellationSignals.get(f) == null) {
                            fragmentStateManager.destroyFragmentView();
                        }
                    }
                    // fall through
                case Fragment.CREATED:
                    if (newState < Fragment.CREATED) {
                        if (mExitAnimationCancellationSignals.get(f) != null) {
                            newState = Fragment.CREATED;
                        } else {
                            fragmentStateManager.destroy();
                        }
                    }
                    // fall through
                case Fragment.ATTACHED:
                    if (newState < Fragment.ATTACHED) {
                        fragmentStateManager.detach();
                    }
            }
        }

        if (f.mState != newState) {
            if (isLoggingEnabled(Log.DEBUG)) {
                Log.d(TAG, "moveToState: Fragment state for " + f + " not updated inline; "
                        + "expected state " + newState + " found " + f.mState);
            }
            f.mState = newState;
        }
    }
}

Fragment 中的所有状态值

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
        ActivityResultCaller {

    static final Object USE_DEFAULT_TRANSITION = new Object();

    static final int INITIALIZING = -1;          // Not yet attached. 初始胡状态
    static final int ATTACHED = 0;               // Attached to the host. 挂载
    static final int CREATED = 1;                // Created. 创建
    static final int VIEW_CREATED = 2;           // View Created. 创建View
    static final int AWAITING_EXIT_EFFECTS = 3;  // Downward state, awaiting exit effects
    static final int ACTIVITY_CREATED = 4;       // Fully created, not started.
    static final int STARTED = 5;                // Created and started, not resumed.
    static final int AWAITING_ENTER_EFFECTS = 6; // Upward state, awaiting enter effects
    static final int RESUMED = 7;                // Created started and resumed.

    int mState = INITIALIZING;
}

从这里可以看出来,通过状态地推,调用 FragmentStateManager类 触发fragment的生命周期的方法被调用

class FragmentStateManager {

  void attach() {
        //  .....代码省略.....
        mFragment.performAttach();
        mDispatcher.dispatchOnFragmentAttached(mFragment, false);
    }
  void create() {
      //  .....代码省略.....
       mFragment.performCreate(mFragment.mSavedFragmentState);
       //  .....代码省略.....
    }
  void createView() {
         //  .....代码省略.....
        mFragment.performCreateView(layoutInflater, container, mFragment.mSavedFragmentState);
        //  .....代码省略.....
        mFragment.mState = Fragment.VIEW_CREATED;
    }
    void activityCreated() {
         //  .....代码省略.....
        mFragment.performActivityCreated(mFragment.mSavedFragmentState);
        mDispatcher.dispatchOnFragmentActivityCreated(
                mFragment, mFragment.mSavedFragmentState, false);
    }
 void pause() {
        //  .....代码省略.....
        mFragment.performPause();
        mDispatcher.dispatchOnFragmentPaused(mFragment, false);
    }

    void stop() {
        //  .....代码省略.....
        mFragment.performStop();
        mDispatcher.dispatchOnFragmentStopped(mFragment, false);
    }
    void start() {
        //  .....代码省略.....
        mFragment.performStart();
        mDispatcher.dispatchOnFragmentStarted(mFragment, false);
    }

    void resume() {
         //  .....代码省略.....
        mFragment.performResume();
        mDispatcher.dispatchOnFragmentResumed(mFragment, false);
    }
}

总结:通过源码的贴出,不能看出Fragment生命周期的就是一个状态的管理,通过FragmentController 发事件分发给FragmentManager 类做状态的递推,触发FragmentStateManager 调用fragment的生命周期

你可能感兴趣的:(从源码角度看 Fragment 生命周期(一))