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

Android 視圖繪制流程(上):View 的測量機制透解

編輯:關於 Android 程式設計

綜述

View 的繪制流程可以拆成三大步:measure(測量自身尺寸)、layout(確定自己在父容器中的位置)、draw(把自己畫到屏幕上)。三者順序固定、缺一不可——沒有尺寸就無從定位,沒有位置也無從繪製。本文聚焦第一步,把 Measure 過程從入口一直追到 FrameLayout 的具體實現。

測量從哪裡開始

整個流程的起點是 ViewRoot(對應 ViewRootImpl 類)的 performTraversals() 方法。它在內部調用 performMeasure() 來測量根 View,而 performMeasure() 又會調用 View 的 measure() 方法。

這裡有個關鍵設計:measure() 被聲明為 final,任何子類都無法重寫。但它在內部調用了 onMeasure(),於是子類通過重寫 onMeasure() 來定制測量邏輯。這是一個典型的模板方法模式——流程不可改,節點可覆寫。因此下面分析的重心就是 onMeasure()。

MeasureSpec:父容器對子 View 的約束

MeasureSpec 是 View 中的一個靜態內部類,它封裝了父佈局傳遞給子佈局的尺寸要求。每一個 MeasureSpec 代表一個方向(寬或高)的要求,本質是一個 32 位整型:高 2 位是 specMode,低 30 位是 specSize。用位運算壓縮存儲,是為了減少對象傳遞中的開銷。

測量模式共三種:

UNSPECIFIED
父容器對子 View 不施加任何限制,子 View 想多大就多大。通常出現在 ScrollView 等可無限滾動的容器中。

EXACTLY
父容器為子 View 指定了一個確切的值,View 最終大小就是 specSize。對應 XML 屬性 match_parent 或寫死具體數值。

AT_MOST
子 View 的大小上限是 specSize,可以更小但不能更大。對應 wrap_content。

創建 MeasureSpec 用靜態方法 makeMeasureSpec(size, mode),讀取則用 getMode() 與 getSize()。

View 的測量過程

先看 View 自己的 onMeasure(),非常精簡:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(
        getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
        getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

它只做一件事:調用 setMeasuredDimension() 把測量結果寫入成員變量。而具體的寬高值由 getDefaultSize() 計算得出:

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
    }
    return result;
}

結果很直白:在 AT_MOST 和 EXACTLY 模式下,測量值直接取 specSize;只有在 UNSPECIFIED 模式下才採用第一個參數 size。而這個 size 來自 getSuggestedMinimumWidth() 與 getSuggestedMinimumHeight():

protected int getSuggestedMinimumHeight() {
    return (mBackground == null) ? mMinHeight
            : max(mMinHeight, mBackground.getMinimumHeight());
}

protected int getSuggestedMinimumWidth() {
    return (mBackground == null) ? mMinWidth
            : max(mMinWidth, mBackground.getMinimumWidth());
}

可以看到,取值取決於 View 有沒有背景。以寬度為例:沒有背景時取 mMinWidth(可通過 XML 的 minWidth 屬性設置,或調用 setMinimumWidth() 賦值,默認為 0);有背景時,則取 mMinWidth 與背景固有最小寬度中的較大值——這保證了比如 NinePatch 背景不會被壓縮到無法顯示。

ViewGroup 的測量過程

ViewGroup 的職責更重:既要測量自己,還要遍歷所有子 View 並逐一觸發它們的 measure,形成遞歸。ViewGroup 本身是抽象類,並沒有重寫 onMeasure(),因為不同佈局(LinearLayout、RelativeLayout、FrameLayout)的測量策略差異極大,無法統一實現。但它提供了 measureChildren() 這個工具方法:

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
    final int size = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < size; ++i) {
        final View child = children[i];
        if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}

邏輯很簡單:跳過 GONE 的子 View,其餘交給 measureChild():

protected void measureChild(View child, int parentWidthMeasureSpec,
                            int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();
    final int childWidthMeasureSpec = getChildMeasureSpec(
            parentWidthMeasureSpec, mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(
            parentHeightMeasureSpec, mPaddingTop + mPaddingBottom, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

核心邏輯都在 getChildMeasureSpec() 裡:它把「父容器的約束 + 父容器已佔用的 padding + 子 View 的 LayoutParams」三者合併,算出傳給子 View 的 MeasureSpec。

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec);
    int specSize = MeasureSpec.getSize(spec);
    int size = Math.max(0, specSize - padding);   // 扣掉 padding 後的可用空間
    int resultSize = 0;
    int resultMode = 0;

    switch (specMode) {
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;  resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;            resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;            resultMode = MeasureSpec.AT_MOST;
            }
            break;

        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                resultSize = childDimension;  resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;            resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;            resultMode = MeasureSpec.AT_MOST;
            }
            break;

        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                resultSize = childDimension;  resultMode = MeasureSpec.EXACTLY;
            } else {
                // MATCH_PARENT 與 WRAP_CONTENT 在此模式下不作區分
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

這段代碼值得反覆讀,它其實是一張「父約束 × 子 LayoutParams」的九宮格決策表:

讀表時記住兩條規律:子 View 寫具體值時永遠是 EXACTLY(父容器再怎麼約束也尊重明確的尺寸);只有父容器是 EXACTLY 且子 View 是 MATCH_PARENT 時,結果才是 EXACTLY。這也解釋了經典難題——「為什麼在 ScrollView 裡用 match_parent 高度沒有效果」:因為此時父容器給的是 UNSPECIFIED,子 View 的 match_parent 被降級成了「自己想多大就多大」。

以 FrameLayout 為例

拿到子 View 的 MeasureSpec 後,各具體佈局就在自己的 onMeasure() 裡完成遞歸。FrameLayout 的實現相對簡單,主要做兩件事:先測量自身,再遍歷子 View 測量。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();
    final boolean measureMatchParentChildren =
            MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY
            || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
    mMatchParentChildren.clear();

    int maxHeight = 0;
    int maxWidth = 0;
    int childState = 0;

    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();

            // FrameLayout 所有子 View 都在同一位置重疊,所以取最大值
            maxWidth = Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
            maxHeight = Math.max(maxHeight,
                    child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
            childState = combineMeasuredStates(childState, child.getMeasuredState());

            // 若自身尺寸尚未確定,先記下用了 MATCH_PARENT 的子 View,稍後二次測量
            if (measureMatchParentChildren) {
                if (lp.width == LayoutParams.MATCH_PARENT
                        || lp.height == LayoutParams.MATCH_PARENT) {
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

    // 加上自身 padding
    maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
    maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

    // 與最小寬高、前景的固有尺寸取較大值
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

    final Drawable drawable = getForeground();
    if (drawable != null) {
        maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
        maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
    }

    setMeasuredDimension(
            resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));

    // 第二輪:為 MATCH_PARENT 的子 View 重新測量
    count = mMatchParentChildren.size();
    if (count > 1) {
        for (int i = 0; i < count; i++) {
            final View child = mMatchParentChildren.get(i);
            final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            final int childWidthMeasureSpec;
            if (lp.width == LayoutParams.MATCH_PARENT) {
                final int width = Math.max(0, getMeasuredWidth()
                        - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                        - lp.leftMargin - lp.rightMargin);
                childWidthMeasureSpec =
                        MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
            } else {
                childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                        getPaddingLeftWithForeground() + getPaddingRightWithForeground()
                        + lp.leftMargin + lp.rightMargin, lp.width);
            }

            final int childHeightMeasureSpec;
            if (lp.height == LayoutParams.MATCH_PARENT) {
                final int height = Math.max(0, getMeasuredHeight()
                        - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                        - lp.topMargin - lp.bottomMargin);
                childHeightMeasureSpec =
                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            } else {
                childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        getPaddingTopWithForeground() + getPaddingBottomWithForeground()
                        + lp.topMargin + lp.bottomMargin, lp.height);
            }
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}

這裡有個值得注意的設計:當 FrameLayout 自身尺寸尚未確定(不是 EXACTLY)時,它無法立刻回答「MATCH_PARENT 的子 View 該多大」,於是先把這些子 View 記下來,等自己測量完成後再補一次 measure()。這就是「兩次測量」的由來,也是為什麼自定義 ViewGroup 時隨意調用 measure() 會引發額外性能開銷。

小結

把整個鏈條串起來:對於普通 View,Measure 非常樸素——拿到尺寸規格,算出數值,寫入成員變量;對於 ViewGroup,則要在此之上多承擔一層責任——遍歷子 View、計算子 MeasureSpec、觸發遞歸。

理解這套機制有直接的實用價值:知道 wrap_content 在自定義 View 中默認不生效(因為 getDefaultSize 直接返回 specSize,需要自行處理 AT_MOST 分支);知道 match_parent 在某些父容器中會失效;也知道為什麼 onMeasure 可能被調用多次。下一篇接著看 layout 與 draw。

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