Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

探究 Android ListView 的緩存機制

從繼承結構說起

ListView 繼承自 AbsListView,而 AbsListView 是所有列表類控件的共同基底。

資料如何被載入

整個流程中最關鍵的函式是 makeAndAddView():它負責取得一個 ChildView 並把它加入清單。邏輯是先看資料有沒有變動,若沒變就優先從 Recycler 取出該位置的現成視圖;找不到才建立新的或重用無用視圖。

private View makeAndAddView(int position, int y, boolean flow, int childrenLeft, boolean selected) {
    View child;

    if (!mDataChanged) {
        //先嘗試取得該位置的現成視圖
        child = mRecycler.getActiveView(position);
        if (child != null) {
            //找到了,直接定位後加入
            setupChild(child, position, y, flow, childrenLeft, selected, true);
            return child;
        }
    }

    //資料已變動:新建視圖,或重用一個已無用的視圖
    child = obtainView(position, mIsScrap);
    setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
    return child;
}

緩存的核心:RecycleBin

當使用者滑動列表,部分已載入的 ChildView 會被暫時移出畫面。為了避免下次再重新載入,layoutChildren() 會被觸發(實際上任何觸碰事件都會走到 onTouchEvent)。真正負責緩存的是 AbsListView 的內部類 RecycleBin,源碼註解已把職責說明得很清楚:

/**
 * The RecycleBin facilitates reuse of views across layouts.
 * The RecycleBin has two levels of storage: ActiveViews and ScrapViews.
 * ActiveViews are those views which were onscreen at the start of a layout.
 * By construction, they are displaying current information.
 * At the end of layout, all views in ActiveViews are demoted to ScrapViews.
 * ScrapViews are old views that could potentially be used by the adapter
 * to avoid allocating views unnecessarily.
 */

ActiveViews 是一次性打包的:呼叫 fillActiveViews() 會把目前所有子視圖一口氣放進 mActiveViews 陣列。

void fillActiveViews(int childCount, int firstActivePosition) {
    if (mActiveViews.length < childCount) {
        mActiveViews = new View[childCount];
    }
    mFirstActivePosition = firstPosition;
    final View[] activeViews = mActiveViews;
    ...
}

ScrapViews 則是逐個加入,透過 addScrapView(),而它又細分兩種等級:

void addScrapView(View scrap, int position) {
    ...
    //帶有 transient 狀態的視圖另外存放
    final boolean scrapHasTransientState = scrap.hasTransientState();
    if (scrapHasTransientState) {
        ...
    } else {
        ...
    }
}

分成 transient(暫態)與一般態,用意是加快取用速度:暫態視圖最有可能是下一個要出現在畫面上的那一個(畢竟使用者滑動的目的就是看下一項)。這在 obtainView() 中獲得印證——它會先找暫態視圖,找不到才找一般 scrap:

View obtainView(int position, boolean[] isScrap) {
    ...
    //優先取得暫態視圖
    scrapView = mRecycler.getTransientStateView(position);
    if (scrapView == null) {
        scrapView = mRecycler.getScrapView(position);
    }
    ...
}

另一個重要角色是 scrapActiveViews():它把 mActiveViews 中剩下的視圖全部降級為 ScrapViews,同時清掉舊的 scrap,並確保 scrap 數量不超過 active 數量。每次 layoutChildren() 都必然呼叫它,目的是清空當前 ActiveViews,為新一輪做準備。

/**
 * Move all views remaining in mActiveViews to mScrapViews.
 */
void scrapActiveViews() {
    ...
    //確保 mScrapViews 不超過 mActiveViews 的大小
    pruneScrapViews();
}

小結

閱讀 ListView 與 AbsListView 源碼後最大的收穫,是理解「兩級緩存 + 暫態優先」的設計如何把視圖建立的成本攤薄。以上僅是起步階段的心得,理解不深之處歡迎指正。

Copyright © Linux教程網 All Rights Reserved