Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

源碼解析 ViewStub:延遲加載是如何實現的

編輯:關於 Android 程式設計

談到布局優化,ViewStub 幾乎一定會被提到。但多數人只是知道要「用它」,卻沒看過它究竟如何運作。本文直接從源碼切入。

官方定義说了什么

打開 ViewStub.java 會發現它就是 View 的子類,並附上一段說明:

A ViewStub is an invisible, zero-sized View that can be used to lazily
inflate layout resources at runtime.

一句話點出三個特性:不可見、零尺寸、可在執行期延遲 inflate。接著看它是怎麼做到這三件事的。

特性一:不可見

建構時會呼叫 initialize():

private void initialize(Context context) {
    mContext = context;
    setVisibility(GONE);
    setWillNotDraw(true);
}

setVisibility(GONE) 讓它在布局載入時就不佔位、不顯示;setWillNotDraw(true) 則保證它的 onDraw() 不會被執行。

但實際上不止於此。ViewStub 還覆寫了父類的 draw()、dispatchDraw() 與 onMeasure():

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(0, 0);
}

@Override
public void draw(Canvas canvas) {
    // 什麼都不做
}

@Override
protected void dispatchDraw(Canvas canvas) {
    // 什麼都不做
}

看到這幾行就明白了:它雖然是個 View,卻完全不測量、不繪製, measure 結果直接是 0×0。這才是「不可見且零尺寸」的真正由來——從源頭上把成本降到最低。

特性二:延遲 inflate

When a ViewStub is made visible, or when inflate() is invoked, the layout
resource is inflated. The ViewStub then replaces itself in its parent with
the inflated View or Views. Therefore, the ViewStub exists in the view
hierarchy until setVisibility(int) or inflate() is invoked.

說明的重點是:一旦设为 visible 或直接呼叫 inflate(),它所對應的布局才會被載入,而且它會把自己從父容器中替換掉。

setVisibility() 的奧妙

public void setVisibility(int visibility) {
    if (mInflatedViewRef != null) {
        View view = mInflatedViewRef.get();
        if (view != null) {
            view.setVisibility(visibility);
        } else {
            throw new IllegalStateException("setVisibility called on un-referenced view");
        }
    } else {
        super.setVisibility(visibility);
        if (visibility == VISIBLE || visibility == INVISIBLE) {
            inflate();
        }
    }
}

邏輯很清楚:若 mInflatedViewRef 已有值,代表曾經 inflate 過,那就把可見性轉發給那個被加載出來的 View;若還是 null 且這次要求可見,就呼叫 inflate()。也就是說,設定可見性這件事本身就是觸發加載的開關。

inflate() 做了什麼

public View inflate() {
    final ViewParent viewParent = getParent();
    if (viewParent != null && viewParent instanceof ViewGroup) {
        if (mLayoutResource != 0) {
            final ViewGroup parent = (ViewGroup) viewParent;
            LayoutInflater factory = (mInflater != null)
                    ? mInflater : LayoutInflater.from(mContext);

            final View view = factory.inflate(mLayoutResource, parent, false);
            if (mInflatedId != NO_ID) {
                view.setId(mInflatedId);
            }

            final int index = parent.indexOfChild(this);
            parent.removeViewInLayout(this);

            final ViewGroup.LayoutParams layoutParams = getLayoutParams();
            if (layoutParams != null) {
                parent.addView(view, index, layoutParams);
            } else {
                parent.addView(view, index);
            }

            mInflatedViewRef = new WeakReference<View>(view);
            if (mInflateListener != null) {
                mInflateListener.onInflate(this, view);
            }
            return view;
        } else {
            throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
        }
    } else {
        throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
    }
}

逐行看關鍵動作:記下自己在父容器中的索引 → 把自己移除 → 在同一個位置插入加載出來的新 View,並沿用原本的 LayoutParams → 用 WeakReference 保存結果 → 通知 listener。

「原位替換」是這裡最漂亮的一手:開發者不必操心新 View 該放哪裡,位置資訊由 ViewStub 自己保管。

mLayoutResource 從哪來

public ViewStub(Context context, AttributeSet attrs, int defStyle) {
    TypedArray a = context.obtainStyledAttributes(attrs,
            com.android.internal.R.styleable.ViewStub, defStyle, 0);
    mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
    mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, 0);
    a.recycle();
    a = context.obtainStyledAttributes(attrs,
            com.android.internal.R.styleable.View, defStyle, 0);
    mID = a.getResourceId(R.styleable.View_id, NO_ID);
    a.recycle();
    initialize(context);
}

也就是 XML 上的 android:layout 與 android:inflatedId 兩個屬性。前者是稍後要載入的布局,後者可讓加載出來的 View 換一個新的 id,避免與佔位階段的 id 混淆。

官方給的用法

ViewStub stub = (ViewStub) findViewById(R.id.stub);
View inflated = stub.inflate();

什麼時候該用它

ViewStub 的價值在於「把不確定是否會用到的介面從初始 inflate 中移出去」。典型場景包括:錯誤提示區塊、網路載入失敗的重試畫面、展開式的進階設定、少數條件才顯示的浮層。這些區塊多數使用者一輩子都不會看到,卻在每次進入頁面時被完整解析一次,白白拖慢啟動速度。

反過來說,若某個區塊幾乎一定會顯示,用 ViewStub 反而多了一層延遲與額外呼叫,得不償失。判斷標準很簡單:使用率低於某個門檻、且布局本身有相當複雜度,才值得包成 ViewStub。此外要注意它只能替換一次, inflate 之後 ViewStub 就已從视图樹中消失,無法重複使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved