Android 9.0 新的Fragment懶加載策略及原理

1 之前使用Fragment懶一般使用fragment.getUserVisibleHint來判斷是否已經(jīng)顯示,今天來說一個更簡便的方式:

FragmentPagerAdapter支持兩種方式,一種是默認(rèn)設(shè)置setUserVisibleHint,另外一種則是使用mCurTransaction.setMaxLifecycle來控制。

//FragmentPagerAdapter源碼如下:
if (mBehavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
mCurTransaction.setMaxLifecycle(fragment, Lifecycle.State.STARTED);
} else {
fragment.setUserVisibleHint(false);
}

今天說是第二種方式:

FragmentViewPagerAdapter mAdapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

這樣的話可以直接在fragment里的onResume()生命周期中加載數(shù)據(jù),比如
@Override
public void onResume() {
super.onResume();
Logger.d(TAG, "onResume");
if (!isLoaded) {
initData();
}
}

數(shù)據(jù)加載成功后,isLoaded設(shè)置為true即可,完全不用當(dāng)心onResume()方法調(diào)用問題!

2 原理:

 重點在FragmentManagerImpl中的代碼:

    if (f.mMaxState == Lifecycle.State.CREATED) {
        newState = Math.min(newState, Fragment.CREATED);
    } else {
        newState = Math.min(newState, f.mMaxState.ordinal());
    }

newState取最小值,默認(rèn)是Lifecycle.State.RESUMED(相當(dāng)于全生命周期),如果你自己設(shè)置值,則會按照你設(shè)置的周期走,而不是每次都走完整的生命周期!

PS:

f.mMaxState.ordinal()是指枚舉的順序,Lifecycle生命周期對應(yīng)如下5個:

public enum State {
    DESTROYED,
    INITIALIZED,
    CREATED, 
    RTED, 
    RESUMED;
}

Fragment的周期對應(yīng)如下:

static final int INITIALIZING = 0; // Not yet created.
static final int CREATED = 1; // Created.
static final int ACTIVITY_CREATED = 2; // Fully created, not started.
static final int STARTED = 3; // Created and started, not resumed.
static final int RESUMED = 4; // Created started and resumed.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容