Navigation之详细聊聊Fragment的实现原理

1. 前语

Fragment真是一个十分老的家伙,它的第一条提交记载是在2010年,而最近的一条记载则是在2021年6月11号,足足11岁了,可是它却老态APP龙钟,在JetpAPPack中大放异彩,Navigation组件便是依据Fragment的一个跳转组件,Google的单Activity项目结构便是一个Actiapplicationvity和多个Fragment项目结appetite构。多approach年以来,一提到Fra业务文书gment,咱们脑海中的第一印象或许还停留在平板应用开发中了,它曾经在app是什么意思手机项目中高频运用Fragment的approach时机还真没那么多。一方面是由于手机项目一般都是多Activity结构完毕的,不会涉及到那么多的Fragment运用java模拟器,另一方面,Fragment也比Activity杂乱,相比之下运用有点费事,甚至是苦楚,欠好定位问题,所以业务文书简报的期数指的是在技能选型时,能避则避。它太难用了,以至于Square团队的Piwai大神(LeakCanary的作者)在2014年发表了一篇主张敌对运用Fragment的文章。不论怎样样,这么多年过去了,Androelementaryid团队也一贯没有扔掉对FragmentElement的支撑,甚至在Jetpack中,GoogleFragment开端扮演越来越重要的人物了,最近关于Navigation的主张运用越来越多了,加上我参与了一个平板项目,所以对Fragment主流程源码进行了一次全面的研讨。收成颇多,相信将来对Navigation研讨定是大有裨益。

2. 创立Fragment

依据官方文档,写一个简略的Demo。简略了解Fragment的运用。

2.1 新建一个Fragment类

class Ejava工作培训班xampleelements什么意思中文Fragment extends Fragmentappetite {
public Example业务所Fragment() {
super(R.layout.example_fragment);
}
}

2.2 把Fragment添加到Activity上

把Fragment添加到Activity上业务文书能够经过xml文件和代码编程两种javascript办法完毕。本文只介绍第二种完毕办法。

<!-- res/layout/example_ac业务局tivity.elementsxml -->
<angoogle商铺droidx.fragment.app.Fragjava言语mentContainerView
xmlns:android="http://schemas.android.com/apk/res/andrapp是什么意思oid"
android:ijava模拟器d="@+id/fragment_container_view"
android:layoujava怎样读t_width="match_parent"
android:layout_hegoogleplay安卓版下载ight="match_parent" />
public class ExaElementmpleActivity extends AppCompatActivity {
public ExampleActivity() {
super(R.layout.example_aelementuictivity);
}
@Override
protected void onCreelements是什么牌子ate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSelements是什么牌子tate);
if (savedInstanceStatelementanimatione == null) {
getSupportFragelements翻译mentManager().beginTrgoogle谷歌查找主页ansactjava难学吗ion()
.setReorderijavascriptngAllowed(true)
.add(R.id.fragment_container_view, ExampleFragment.class, null)
.commit();
}
}
}

咱们能够看到,主要是经过FragmentManager来将Fragment增java怎样读加到fragment_container_view对应的布局中,Demo是蛮简略的,模板代码业务的四个特性,网上仿制一下就能用。可是FragmentManager、Transaction、commit()分别是什么意思,还有待深化根究一番。

3. 深化了解Fragment原理

3.1 Fragment实质是什么

3.1.1 Fragment实质是Viewappreciate

早年面的DEMO咱们看到,Fragment会adjava面试题d到FragmentContainerView上面,能被添加到ViewGrojava工作培训班up的组件,必定也是View或许ViewGroup。有源码为appear证:

//androidx.fragment.app.Fragment.java
ViewGroup mContaigoogle网站登录进口ner;
// The Vieelementuiw generated for this fragmentgoogle谷歌查找主页.
Viewelementanimation mView;

那么既然如此,何须大费周章呢,直接用View来替代F业务的四个特性ragmentelements什么意思中文不就好了,addView()、removeView()运用起Element来更简略直观。

当然了Fragment实质是View可是又不只限于此, 在真实的项目中,界面往往很杂乱,业务逻辑也很杂乱,往往需求处理各种UI状况改动,比如:添加一组Vigoogle浏览器ew,替换一组View,删去一组View,还需求和Activity协作。总之,假定让开发者自己去完毕这一套逻辑,恐怕比运用Fragment要费事的多吧。虽然Fragment看起来蛮杂乱的,可是仍是远比咱们自己去完毕相同功用简略的多。

3.1.2 Felementuiragment实质不只限于View

Fragment作为一个View能够google空间业务所添加到Activity的布局中去。可是他更强壮,还有以下几个特性:

  1. 处理生命周期,比Activity生命周期还要杂乱
  2. 经过FrJavaagmentTransaction操作多个Fragment
  3. 经过FragmentManager保护一个回退栈,回退到上一个FragmentTransaction操作的界面
//androidx.fragment.app.Fragment.java
static final i业务文书nt INITIALIZING = -1;          // Not yet attacapp下载hed.
static final int AelementaryTTACHED = 0;               // Attached to the host.
static final int CREATED = 1;                // Created.
static final int VIEW_CRE业务文书简报的期数指的是ATEjava初学D = 2googleplay;           // View Created.
statelement滑板ic final int AWAITING_EXIT_EFFECTS = 3;  // Downwarjavaeed statelementuie, awaiting exit effects
static finalgoogle谷歌查找主页 int ACTIVITY_CREATED = 4;       // Fully created, not started.
static final int STARTED = 5element滑板;                // Created and started, not resumed.
static final in业务阻隔等级t AWAITING_ENTER_EFFECTS = 6; // Upward selements是什么牌子tate, awaiting enter effects
static final int RESUMED = 7;                // Created started and resumed.

从代码咱们能够看出,有8种状况。分为两类,View相关的以及和Activity情java怎样读况相关的。后文会具体介绍,此处点到为止。

3.2 FragmentTransactapp下载ion

3.2.1 FragmentTransaction概述

软件工程中有一门叫数据库的课程,数据库中有一业务文书个叫”业务”的概念,它标明多elementui个操作google网站登录进口是原子性的,要么一起成功,要么业务性工作一起失利,典型的appreciate比如便是转账,张三给李四转账100元这么一个业务,存在两个操作,从张三的账户中扣除100元,给李四的账户添加Java100元。由于有了业务,不会存在只需某一个操作成功,elementui而另一个操作失利的状况,否则后果不堪设想。

在Android中SharedPreferencegoogle谷歌查找主页也有commit办法。

SharedappetitePreferences sharedPreferences= getSharedPreferences("data",Context.MElementODE_PRIVATE);
SharedPreferences.Editor editor =业务 sharedPreference业务阻隔等级s.edit();
editor.putString("name", “Tom”);
editor.putInt("age", 28);
editor.putBoolean("marrid",false);
editor.commit();

上述功appetite用,一次提交做了三件事情,putString,putInt,putgoogle翻译Boolean。

而FragmentTransaction和SharedPrefereelements是什么牌子nce相似。它能够一起操作多个Fragment。

假定elementanimation有布局文件如下:

<LinearLayout android:orientagoogle浏览器tion="vertical">
<ViewGroup1>
<Fragment1 />
<google谷歌查找主页/ViewGroup1>
<ViewGroup2appstore>
&lt业务所是干什么的;Fragment2 />
</ViewGroup2>
<ViewGroup3&app下载gt;
<Fragment3 />
</ViewGroup3>
</LinearLappearayout>

假定咱们想在ViewGroup1上添加Frapproachagment1,ViewGroup2上用Fragment2替换掉,把ViewGroup3上的Fragment移除掉。

伪代码如下:

getSupportFragmentManager().beginTransactappointmention()
.setReorderingAllowAPPed(true)
.add(ViewGelement滑板roup1, Fapp下载ragmengoogle地球t1.class, null)
.replace(ViewGroup2,Fragment2.class,null)
.remove(Fragme业务阻隔等级nt3)
.commit();

问:这三个操作我为什google网站登录进口么要放到一个业务中呢业务性告诉?我连续实施这三个操作不行吗?

答:有业务性告诉些场景下能够,有些场景下不能够。涉及到回退栈的时分,是否放到业务中,按回来键会有很大的差异。咱们把上述三个操作分别命名为OP1、OP2、OP3。假定调用了FragmentTragoogle翻译nsaction.addToapplicationBackStack(),三个操作放到业务中时, 按回来键时会实施与OP1、OP2、OP3相反的操作,即ViewGroup1、ViewGroup2、ViewGroup3一起康复到处理业务之前的状况。假定三个操作不放到业务中时, 则会依次康复 ViewGroup3、Velements什么意思中文iewGroup2、ViewGroujavaeep1的状况

3.2.2 FragmentTransaction源码剖析

3.2.2.1 支撑的操作OP_CMD

//FragmentTransaction.java
static final int OP_NULL = 0;
static final int OP_ADD = 1;
static final int OP_REPLACE = 2;
static fina业务性工作是什么意思l int OP_REMOVE = 3;
static final业务所是干什么的 int OP_HIDE = 4;
static final int OP_SHOW = 5;
static finajavascriptl iElementnt OP_DETACH = 6;
static final int OP_ATTACH = 7;
static final igoogle商铺ngoogle网站登录进口t OP_SET_PgoogleRIMARY_NAV = 8;
static final int OP_UNSET_PRIMARY_NAV = 9;
static final int OP_Sapp是什么意思ET_MAX_LIFECYCLE = 10;

挑几个一眼就能看懂的。

  1. OP_ADD标明添加Fragment
  2. OP_REPLACE标明替换某个ViewGroup上的Fragmen业务t
  3. OP_REMOVE删去Fragment
  4. OP_HIDE躲藏Fragment,等同于View.setVisibi业务文书lity(View.GONE)
  5. OP_SHOW显现Frag业务文书ment,等同于View.setVisibility(View.VISIBLE)
  6. OP_DETACH detach Fragment
  7. OP_ATTACH attach Fragment

对应的办法分别是:

//FragmentTransaction.java
public FragmentTelements什么意思中文ransactionJava add(@NonNelementuiull Fragapp是什么意思ment fragment, @Nullable String tag)  {
doAddOp(0, fragment, tag, OP_ADDgoogle空间);
return this;
}
public FragmentTransaction replace(@IdRes int contai业务局nerViewId, @NonNull Fragment fragment) {
return replace(containerViewId, fragment, null);
}
public FragmentTraelementanimationnsaction remove(@NonNull Fragment fragment) {googleplay安卓版下载
addOp(new Op(OP_REMOVE, fragment));
return tgoogleplayhis;
}

3.application2.2.2 OP类

public abstract class FragmentTragoogleplaynsaction {
ArrayList<Op> mOps = new ArrayList<>();
static final class Op {
int mCmd;
Fragment mFragment;
int mEnterAnim;APP
intgoogleplay mExitAnim;
int mPopEnterAnim;
int mPopExitAnim;
Lifecycle.State mOldMaxState;
Lapp是什么意思ifecycle.State mCurrentMaxState;java工作培训班
Op() {
}
Op(int cmd, Fragment fragment) {
this.mCmd = c业务阻隔等级md;
this.mFragment = fragment;
this.mOldMaxState =appreciate Lifecycle.State.RESUMED;
this.mCurrentMaxState = Lifecycle.State.RESUMED;
}
Op(int cmd, @NonNull Fragment fragment, Lifecycle.State state) {
thisElement.mCmd = cmd;
this.mFragment = fragment;
this.mOldMaxState = fragment.mMaxState;
this.mCurrentMaxState = state;
}
}
}

从源码中咱们能够看到,FragmentTransaction中有ArrayList<Op> mOps。它标明一个业务中需求处理几个操作。而OappstoreP类最重要的两个字段便是mCappreciatemd和mFrjava怎样读agment。标明对某个Fragment实施googleplay指定的操作。

3.2.2.element什么意思3 FragmentTransact业务ion.commit()办法

//FragmentTransaction.java
public abstract class FragmentTransaction {
public abstract int commit();
}

咱们看到commit()办法是个笼统办法。它由BackStackRecord类完毕。

final claappetitess BackStackRecord extends FragmentTransaction implements
FragmentManagejava面试题r.BackStackEntry, FragmentMaelements什么意思中文nager.Op业务文书Generator {
@Override
publicjava怎样读 int commit() {
return commitInternal(fagoogle空间lse);
}
}

3.3 BackStackRecord

3.3.1 BackStackRecord概述

BackStackRecord是FragmentTransaction的子类,标明它支撑一起操作多个Fraapplegment。一起,断章取义,它会被放到BackStack(回退栈)中。回退栈定义在FragmentManager中,是一个ArrayList集结。

//FragmentManager.java
ArrayLiAPPst<Baelements什么意思中文ckS业务文书简报的期数指的是tackRec业务的四个特性ord> mBaappstoreckStack;

一言以蔽之,BackStackReco业务局rd支撑业务操作,一起又会被放入到回退栈中

3.3elements什么意思中文.2 BackStackRecord commit流程

int commitInternal(boolean allowStateLoss) {
if (mCommitted) throw new Illegaelements翻译lStateException("commit already called");
if (FragmentManageappler.isLoggingEnabled(Log.VERBOSE)) {
Log.v(Tjava难学吗AG, "Commit: " + this);
LogWriter logw = new LogWriter(TAG);
PrintWriter pw = new PrintWriter(logw);
dump("  ", pw);
pw.close();
}
mCommitted = true;
if (mAddToBackStack) {
mIndex = mManager.allocBackStackIndex();
} else {
mIndex = -1;
}
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}

该办法最主要的便是调用了FragmentManager.enqueueAction办法

3.4 FragmentManager

3.4.1 FragmentManager概述

早年文,咱们知道,对多个Fragment的操作会被记载到FragmentTransaction中,究竟调用Fragme业务的四个特性ntManager.enqueueAction办法,真实实施Fragment操作。

3.4.2 操作调用流程

1. FragmentManager.enqueueAction()

voapp下载id enqueueelementanimationAction(@NonNull OpGenerator action, boolean allowStateLoss) {
if (!allowStategoogle谷歌查找主页Loss) {
if (mHost == null) {
ifgoogle翻译 (mDestroyed) {
throw new IllegalStateException("FragmentManager has been destroyed");
} else {
throw new IllegalStateException("FragmentManager has not been attached to a "
+ "host.");
}
}elementary是什么意思
checkStateLoss();
}
synchronized (mPendingActions) {
if (mHost == null) {
if (allowStateLoss) {
// This FragmentManager isn't attached, so drop the entire transaction.
retgoogleplay安卓版下载urn;
}
throw new IllegalStateappointmentException("Activity has been destroyed");
}
mPendingActions.add(action);
scheduleCommit();
}
}

该办法究竟调用到scheduleCommit()办法

2. FappetiteragmentManager.scheduleCommappleit()

void scheduleCommit() {
synchronized (mPendingActions) {
boolean postponeReady =
mPostponedTransactions != null && !mPostponedTransactions.isEmpty();
boole业务文书简报的期数指的是an pendingReady = melements什么意思中文PendingActions.size() == 1;
if (posgoogle谷歌查找主页tponeapplicationReady || pendingReady) {
mHost.getHandle业务文书简报的期数指的是r().removeCallba业务文书cks(mExecCommit);
mHost.getHandler().post(mExecCommit);
updateOnBackPresseelementuidCallbackEnabled();
}
}
}

该办法究竟经过Handler业务实施mExecCommit

3. FragmentMgoogle网站登录进口anaelement什么意思ger.mExecCommit

private Runnable mExecCommi业务所是干什么的t = new Runnable() {
@Ovelementanimationerride
public void run() {
execPendijava言语ngappointmentActions(true);
}
};

该办法究竟调用execPendingActions

4. FragmentManager.execPendingActions()

boolean exgoogle空间ecPendingActions(boolean allowStateLoss) {
ensureExecReady(allowStaGoogleteLoss);
boolean didSomething = false;
while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) {
mExecutingActions = true;
try {
removeRedjavascriptundantOperationsAndExecute(mTmpRecords, mTmpIsPop);
} finallelementsy {
clGoogleeanuAPPpExec();
}
didSomething = true;
}
updateOnBackPressedCallbackEnabled();
doPendingDeferredStart();
mFragmentStore.burpActive();
return didSomething;
}

关键重视removeRedundantOperationsAnelement滑板dExecute(mTmpRecords, mTmpIsPop)

5. FragmentManager.removeRedundantOperationsAndExecujava言语te()

private void remove业务所RedundantOpeapp下载rationsAndExecute(@NonNull ArrayList<BackStackRecgoogleplay安卓版下载ord> records,
@NonNull ArrayList<Boolean> isRecordPop) {
}

办法比较长省掉代码,究竟调用exappreciateecuteOpsTogether

6. FragmentManageappreciater.executeOpsjava模拟器Together

prijava模拟器vate void ex业务所是干什么的ecuteOpsTogether(@NonNjava怎样读ull ArrayList<BackStackRecord&ggoogle商铺t; records,
@NonNull业务性工作是什么意思 Arrgoogle浏览器ayList<Boolean> isRecordPop, int startIndex, int endIndex) {
}

办法比较长省掉代码,究竟调用executeOps办法

7. FragelementanimationmentManager.executeOps()

private sta业务所tic void executeOps(@NonNullAPP Arrajava言语yList<BackStacappetitekRecojava面试题rd> records,
@NonNull ArrayList<Booleajava模拟器n> isRegoogleplaycordP业务op, inElementt startIndex, int endIndex) {
for (igoogle商铺nt i = startIndex; i < endIndex; i++) {
final BackStackRecord record = records.get(i);
final boolean isapplicationPop = isRecordPop.get(i);
if (isPop) {
record.bumpBackStackN业务文书简报的期数指的是esting(-1);
// Only execute the add operations at the end of
// all transactions.
boolean moveToState = i == (endInde业务的四个特性x - 1);
record.executePopOps(moveToState);
} elselementarye {
record.bumpBackStackNesting(1);
record.executeOps();
}
}
}

该办法appointment分为两种状况,入栈和出栈,对应commit()和FragmentManager.popBackStack()操作。

8. FragmentManager.executeOps()

void executeOps() {
final int numOps = mOps.siappetiteze()业务所是干什么的;
for (int opNum = 0; opNum < numOps; opNum++) {
final Op op = mappearOps.get(opNum);
final Felements翻译ragment f = op.mFragment;业务
if (f != null) {
f.setPopDirection(false);
f.setNextTransition(mTransition);
f.setSharedElementNames(melements是什么牌子SharedElementSappstoreourceNames, mSharedElementTargetNames);
}
switch (op.mCmd) {
case OP业务文书简报的期数指的是_ADD:
f.setAnimations(op.mEntejavaeerAnim, op.mExitAnim, op.mPopEnterAnim, op.mPopExitAnim);
mManager.setExiapplicationtAnimationOrder(f, false);
mManagGoogleer.addFragment(f);
break;
case OP_REMOVE:
f.setAnimations(op.mEappetitenterAnim, op.mExitAnim, op.mPopEnterAnim, op.mPopExitAnim);
mManager.removeFragment(f);
break;
case OP_HIDE:
f.setAnimations(op.mEnterAnim, op.m业务局ExitAn业务性工作是什么意思im, opelements是什么牌子.mPopEnterAniappointmentm, op.mPopExitAnim);
mManager.hideFragment(f);
break;
case OP_SHOW:
f.setAnimations(op.mEnterAnim, op.mExitAnim, op.mPopEnterAnim, op.mPopExitAnim);
mManager.setExitAnimationOrder(f, false);
mManager.showFragment(f);
break;
case OP_DETACH:
f.setAnimationselements翻译(op.mEntelementary是什么意思erAnim, op.mExitAnim, op.mPopEnterAnim, op.mPopExitAnim);
mManaggoogle翻译er.detachFragment(f);
break;
cas业务文书简报的期数指的是e OP_ATTACH:
f.setAnimat业务性告诉ions(op.mEnterAnim, op.mExitAnimelements,googleplay安卓版下载 op.mPopEnterAnim, op.mPopExitAnim);
mManager.setExitAnimationOrder(f, false);
mManager.attachFragment(f);
break;
case OP_SET_PRIMARgoogle地球Y_NAV:
mManager.setPrimaryNavigationFragment(f);
bjava怎样读reak;
case OP_UNSET_PRIMAelement滑板RY_NAV:
mManager.setPrimaryNavigationFragment(null);
break;
case OP_SET_google空间MAX_LIFE业务局CYCLE:
mManager.setMaxLifecycle(f, op.mCelementary是什么意思urrentMaxState);
break;
default:
throw new IllegalArgumentException("Unknown cmd: " + op.mCmd);
}
if (!mReorderingAllowed && op.mCmd != OP_ADDapp是什么意思 && f != ngoogle谷歌查找主页ull) {
if (!FragmentManager.USE_STATE_MANAGER) {
mManager.moveFragmentTogoogleplay安卓版下载ExpectedapproachState(f);
}
}
}
if (!mReorderingAllowed &&amgoogle网站登录进口p; !FragmentManager.USE_STATE_MANAGER) {
// Added fragmeGooglents are added at the end to comply with prior behavior.
mManager.mov业务性工作eToState(mManager.mCurState, true);
}
}

该办法做了两件事,其一:依据OP.mCmd,操作F业务的四个特性ragmentManager对应的办法,该进程并不会真实实施操作,也只是做记载操作,其二:调用mManager.moveToState(mManager.mCurState, tr业务文书简报的期数指的是ue)

究竟会调用到mGoogleManager.moveToState(Fragment f, int newState)办法,它是Fragmgoogle翻译ent结构中真实中心办法

3.5 FragmejavaeentManager的中心办法void moveToState(Fragment f, int newState)

作为中心办法,并没有放在3.4章节中,只是为了超卓它的中心地位。

void moveToState(@NonNull Fragment f, int newState) {
FragmentStateManager fragmentStateManager = mFragmentStore.getFragmentStateManager(f.mWho);
if (fappetiteragmentStateManager == null) {
// Ideally, we only call moveToState() on active Fraggooglements. However,
// igoogle翻译n restoreSaveState() we can call moveToState() on retained Fragments
// just to clean them up without them ever being added to mActive.
// For these cases, a brand new FragmentStateManager is enough.
fraElementgmentStateManager = new FragmentStateManager(mLifecycleCallbacksDispatcher,
mFragmentStore, f);
// Onelements什么意思中文ly allow this FragmentStjavaeeateManager to go up to CREAgoogle商铺TED at the most
fragmentStateManager.setFragmentManagerState(FragAPPment.CREATED);
}
// Whelement滑板en inflating an Activity view with a rejava模拟器source instead of using setContentView(), and
// that resource adds a fragment us业务性工作ing the <frjavaapi中文在线看agment> tag (i.e. from layout and in layout),
// the frelement滑板agment will move to the VIEW_CREATED state before the fragment manager
// moves to CREATED. So when moving the fraGooglegment manager moves to CREATED and the
// inflated fragment is already in VIEW_CREATED we need to move new state up from CREATED
// to VIEW_CREATED. This avoids accidentally moving the fragmengoogle谷歌查找主页t back down to CREATED
// which would immediately destroy the Fragment's view. We rely on computeExpectedState()
// to pull the state back down if needed.
if (f.mFrjavaapi中文在线看omLayout && f.mInLayout && f.mState == Fragment.VIEW_CREATED) {
newStateelement滑板 = Math.max(newStaGooglete, Fragment.VIEW_CREAgoogleplayTED);
}
newState = Math.min(newState, fragmentStateManager.computeExpectjavascriptedState(google浏览器));
if (f.mState <= newState) {
// If we are moving to the same state, we do not need to give up onjavaapi中文在线看 the animation.
if (f.mState < newState && !mExitAnimationCancellaappreciatetionSignals.isEmpty()) {
// The fragment is currently being animateAPPd...  but!  Now we
// want to moveelementary our stateappreciate back up.  Give up on waiting for the
// animation and proceed from wherjavascripte we are.
cancelExitAnelements翻译imation(f);
}
switch (f.mState) {
case Fragment.INITIALIZING:
if (newState > Fragment.INITIALjavaeeIZING) {
felements什么意思中文ragoogle浏览器gmentStateManager.attach();
}
// fall through
case Fragment.ATTACHED:
if (newStatappstoree > Fragment.ATTACHED) {
fragmentStateManager.create();
}
// fall through
cgooglease Fragment.CRE业务所Aelement滑板TED:
// We want to uncelementsonditionally run this anytime we do a moveelement什么意思ToState that
// moves业务性告诉 the Fragment above INITIALIZING, including cases such as wheelementanimationn
// we move from CREATED => CREATED as part of the case fal业务文书简报的期数指的是l through above.
if (neapp下载wState > Fragment.INIapp下载TIALIZING) {
fragmentStateMgoogleplay安卓版下载anag业务局er.ensureInflatedViewjava难学吗();
}
if (newState > Fragmapplicationent.CREATED) {
fragmentStateManager.createView();
}
// fall through
case Fragment.VIEW_CREA业务所是干什么的TED:
if (newState > Fragment.VIEW_CREATED) {
fapp是什么意思ragelements翻译mentStateManager.activityCreated();
}
// fall through
case Fragment.ACTIVITY_CREATED:
if (newState &Javagt; Fragment.ACTIVITY_CREATED) {
fragmentStateManager.start();
}
// fElementall through
case Fragment.STARTED:
if (nelements什么意思中文ewState > Fragment.STARTED) {
frjavaeeagmentStateMgoogle商铺anager.resume();
}google网站登录进口
}
} else if (f.mState > newState业务所) {
swelementanimationitch (f.mSjavaapi中文在线看tate) {
case Fragment.RESUMED:
if (newState < Fragment.RESUMED) {
fragmentSgoogle浏览器tateManager.pause();
}
// fall through
cgoogle商铺ase Fragment.STARTED:
if (newState < Fragment.STARTED) {
fragmentStateManager.stjavascriptop(业务局);
}
/业务的四个特性/ fall through
case Fragmentjavaee.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 ngoogle翻译ot
// done业务文书 already.
ifgoogle网站登录进口 (mHost.onShouldSaveFragmentState(f)google网站登录进口 && f.mSavedViewState == null) {
fragmentStateManager.saveViewState();
}
}
}
/appreciate/ fall through
case Fragment.VIEW_CREATED:
if (newState < Fragment.VIEW_CREATED) {
FragmentAnim.Animatapp下载ionOrAnimator anelement滑板im = nullapproach;
if (appearf.mView != nappearulljava难学吗 && f.mContelement滑板ainer != null)google谷歌查找主页 {
// Stop any current animations:
f.mContainer.endViewTransitappleion(业务性工作是什么意思f.mView);
f.mVijava言语ew.clearAnimation();
// If parent is being removed, no need to handle child animations.
if (!f.isRemovingParent()) {
if (mCurState > Fragment.INITIALIZING && !mDestroyed
&& f.mView.getVisigoogle商铺bility() == Vjavascriptiew.VISIBLE
&& f.mPostponedAlpha >= 0) {
anim =apple FragmentAnim.loadAnimation(mHost.getContext(),
f, false, f.getPopDirection());
}
f.mPostponedAlpha = 0;
// Robolectric tests do not post the animationgoogle商铺 like a real device
// so we should keep up with the conelements什么意思中文tainer and view in case the
// fragoogle网站登录进口gment view is degoogle谷歌查找主页stroyed before we can remove it.java难学吗
ViewGrogoogle翻译up container = f.mContainer;
View view = f.mView;
if (anim != null) {
Frajava言语gmentAnim.animateRemoveFragment(f, aapp下载nim,
mFragmentTransitapproachionCallback);
}
container.removeViewjava怎样读(view);
if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) {
Log.v(FragmentManager.TAG, "Removing view " + view + " for "
+ "fragmenapp是什么意思t " + f + " from contaiapplicationner " + container);
}
// If theGoogle local container is different froelementarym the fraappreciategment
// container, that means onAnimationEnd was called, onDestroyView
// was dispatched and the fra业务文书g业务ment was already moved to state, so
// we should earlygoogle浏览器 return here instead of attempting to move tojava模拟器
// state again.
if (container != f.mContaine业务阻隔等级r) {elementanimation
return;
}
}
}
// Ifjavascript a fragment has an exit animation (or transition), do not destroy
// its view immediately and sejava初学t the state after animatGoogleing
if (mElementExitAnimationCancellationSignals.get(f) == null) {
fragmentStateManager.destroyFragmentView();
}
}
// fal业务文书简报的期数指的是l through
case Fragment.CREATED:
if (newState < Fragment.CREATED) {
if (mExitAnimationCappetiteancellationSignals.gappstoreet(f) != null) {
// We are waiting for the fragment's view to finish animating away.
newState = Fragment.CREAappointmentTED;
} else {
fragmentStateManager.destroy();
}
}
// fall through
case Fragment.ATTACHED:
if (newState < Fragment.ATTACHED) {
fraapplicationggoogle翻译mentStateManager.detach();
}
}
}
ifAPP (f.mState != newStat业务所e) {
if (isLoggingEnabled(Log.DEBUG)) {
Log.element滑板d(TAG, "mojava面试题veToState: Fragment state for " + f + " not ugoogle地球pdated inlappetiteine; "
+ "expected state " + newState + " found " + f.mState);
}
f.mState = newState;
}
}

该办法是整个Fragment结构中的业务的四个特性中心办法,它会依据政策state和Fragment当前的state一步一步的晋级或降级Fragment的State。究竟回调到Frgoogle商铺agment的相关生命周期办法。 至此整个commit办法的调用链条就剖析完毕了。

由于篇幅有限,mManager.业务moveToState(Fragment f, int newState)我将新写一篇文章,专门图解一番。其实LifeCycle组件的Statelementary是什么意思e改动也elements是相似的,一步一google翻译步晋级或降级

肝文不易,想学习更多干货知识,请重视”字节小站”群众号,假定有疑问,欢迎参与”字节小站交流群”交流讨论,让咱们碰撞出更多考虑吧。

Navigation之具体聊聊Fragment的实现原理

发表评论

提供最优质的资源集合

立即查看 了解详情