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

Android View 系統原始碼解析:measure 流程與 MeasureSpec 全拆解

編輯:關於 Android 程式設計

作為 Android 開發者,我們都知道一個 View 從無到有會經歷三個階段:

  1. measure(測量):確定這個 View 有多大。
  2. layout(布局):確定它的左上右下座標。
  3. draw(繪製):按前兩步的結果,把 View 畫在螢幕上對應的位置。

今天要深入看的是第一步。大部分人都知道 measure 是從 ViewRootImpl.measureHierarchy 開始,歸根結底則是從 performTraversals 觸發。但一個更根本的問題是:onMeasure(int widthMeasureSpec, int heightMeasureSpec) 這兩個參數到底從哪裡來?我們都知道它們代表 parent 施加的約束,可程式跑起來時,這些值究竟是怎麼產生的?

要回答這個問題,得從 ViewRootImpl.measureHierarchy 的源碼說起。

一、measureHierarchy:根視圖的測量起點

private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
        final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {

    int childWidthMeasureSpec;
    int childHeightMeasureSpec;
    boolean windowSizeMayChange = false;

    boolean goodMeasure = false;

    if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
        // WRAP_CONTENT 的情況下,先從一個 prefered 值開始 measure。
        // 在大螢幕上,我們不希望對話框為了顯示一行文字就 stretch 滿整個寬度,
        // 所以先試一個比較小的尺寸看看能否容納。
        final DisplayMetrics packageMetrics = res.getDisplayMetrics();
        res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);

        int baseSize = 0;
        if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
            baseSize = (int) mTmpValue.getDimension(packageMetrics);
        }

        if (baseSize != 0 && desiredWindowWidth > baseSize) {
            // 如果 baseSize 比較小,先用它 measure 一遍試試
            childWidthMeasureSpec  = getRootMeasureSpec(baseSize, lp.width);
            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

            if ((host.getMeasuredWidthAndState() & View.MEASURED_STATE_TOO_SMALL) == 0) {
                goodMeasure = true;      // 結果合適
            } else {
                // 放不進去,加大 baseSize 重新來過
                baseSize = (baseSize + desiredWindowWidth) / 2;
                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

                if ((host.getMeasuredWidthAndState() & View.MEASURED_STATE_TOO_SMALL) == 0) {
                    goodMeasure = true;
                }
            }
        }
    }

    if (!goodMeasure) {
        // 用 baseSize 測出來不合適,就老老實實用傳入的參數重新測一遍
        childWidthMeasureSpec  = getRootMeasureSpec(desiredWindowWidth, lp.width);
        childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

        if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
            windowSizeMayChange = true;
        }
    }

    return windowSizeMayChange;
}

這裡有個容易被忽略的細節:WRAP_CONTENT 的窗口並不是一次就測到位,而是先用一個偏小的 baseSize 試探,若放不下就把 baseSize 與目標寬度取中點再試一次。這種「先小後大」的策略,是為了避免一個只顯示一行字的對話框被拉滿整個螢幕寬度。

二、getRootMeasureSpec:MeasureSpec 的誕生

/**
 * 依根視圖的 LayoutParams 計算出 window 中根視圖該用的 MeasureSpec。
 *
 * @param windowSize    視窗可用的寬或高
 * @param rootDimension 視窗某個維度(寬或高)的 LayoutParams
 */
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
    int measureSpec;
    switch (rootDimension) {
        case ViewGroup.LayoutParams.MATCH_PARENT:
            // 視窗不能縮放,強制 root view 就等於 windowSize
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;

        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // 視窗可以縮放,root view 最多就是 windowSize
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;

        default:
            // 指定了具體數值,強制 root view 為該大小
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
    }
    return measureSpec;
}

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
    try {
        // 呼叫 root view 的 measure,從此進入 view 層次結構,
        // 順便也把 MeasureSpec 帶了進去
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

這就是我們論證的起點:MeasureSpec 是由 window 的可用尺寸,加上 XML 中指定的 LayoutParams,兩者協商而來的。你在 XML 寫的 layout_width,最終就是透過這裡變成一個 32 位元整數——高 2 位是 mode,低 30 位是 size。

三、View.measure:final 方法與快取機制

DecorView 實際上繼承自 FrameLayout,而它和 ViewGroup 都沒有覆寫 measure(),也沒法覆寫——這是 View 的一個 final 方法:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    boolean optical = isLayoutModeOptical(this);
    if (optical != isLayoutModeOptical(mParent)) {
        Insets insets = getOpticalInsets();
        int oWidth  = insets.left + insets.right;
        int oHeight = insets.top  + insets.bottom;
        widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
        heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
    }

    // 把兩個 spec 組合成一個 long 作為快取 key
    long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;

    if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

    if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT
            || widthMeasureSpec != mOldWidthMeasureSpec
            || heightMeasureSpec != mOldHeightMeasureSpec) {

        // 先清除 measured dimension 旗標
        mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
        resolveRtlPropertiesIfNeeded();

        int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT
                ? -1 : mMeasureCache.indexOfKey(key);

        if (cacheIndex < 0 || sIgnoreMeasureCache) {
            // 自己測量,這一步會把 measured dimension 旗標設回來
            onMeasure(widthMeasureSpec, heightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        } else {
            // 命中快取,直接取用
            long value = mMeasureCache.valueAt(cacheIndex);
            setMeasuredDimension((int) (value >> 32), (int) value);
            mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        // 若旗標沒被設上,代表子類忘了呼叫 setMeasuredDimension(),直接拋例外
        if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
            throw new IllegalStateException("onMeasure() did not set the"
                    + " measured dimension by calling"
                    + " setMeasuredDimension()");
        }

        mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
    }

    mOldWidthMeasureSpec  = widthMeasureSpec;
    mOldHeightMeasureSpec = heightMeasureSpec;

    mMeasureCache.put(key, ((long) mMeasuredWidth) << 32
            | (long) mMeasuredHeight & 0xffffffffL);
}

這裡有兩個值得記住的重點。第一,measure() 帶了一份快取:如果 spec 沒變也沒有 FORCE_LAYOUT 旗標,就直接回傳上次的結果,不再重新測量。這解釋了為什麼某些「改了內容但尺寸沒變」的場景需要明確呼叫 requestLayout() 才會生效。

第二,那個 IllegalStateException 檢查:自訂 View 覆寫 onMeasure() 時必須呼叫 setMeasuredDimension(),否則就會在這裡炸掉。這是新手自訂 View 最常踩的坑之一。

四、View.onMeasure:預設實作

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

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
    boolean optical = isLayoutModeOptical(this);
    if (optical != isLayoutModeOptical(mParent)) {
        Insets insets = getOpticalInsets();
        int opticalWidth  = insets.left + insets.right;
        int opticalHeight = insets.top  + insets.bottom;
        measuredWidth  += optical ? opticalWidth  : -opticalWidth;
        measuredHeight += optical ? opticalHeight : -opticalHeight;
    }
    mMeasuredWidth  = measuredWidth;    // 賦值
    mMeasuredHeight = measuredHeight;
    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;   // 設置旗標
}

protected int getSuggestedMinimumHeight() {
    // 沒有 background 時回傳 mMinHeight(可在 XML 中指定),
    // 否則回傳 mMinHeight 與 background 最小值中的較大者
    return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}

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

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:
            // parent 沒指定,則用自己的 default size
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            // 無論是精確指定或至多,都用 spec 提供的值
            result = specSize;
            break;
    }
    return result;
}

注意 getDefaultSize() 的行為:當 specMode 是 AT_MOST 時,它直接回傳 specSize,也就是「parent 給的上限」。這正是 wrap_content 在自訂 View 中常常變成「跟 parent 一樣寬」的根本原因——預設實作根本沒有去計算內容的實際大小。

所以官方文件才會強調:子類應該覆寫 onMeasure() 以提供對自身內容更準確的測量。ViewGroup 本身沒有提供 onMeasure 實作,但提供了幾個測量過程中很有用的工具方法,供 FrameLayout、LinearLayout 等子類使用。

五、FrameLayout.onMeasure:容器如何測量子元素

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();

    // 是否為 match_parent 的子元素
    final boolean measureMatchParentChildren =
            MeasureSpec.getMode(widthMeasureSpec)  != MeasureSpec.EXACTLY
         || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;

    mMatchParentChildren.clear();

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

    // 遍歷 children,找出 maxWidth / maxHeight,順便建立 mMatchParentChildren 列表
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        // 預設只 measure 非 GONE 的 child
        if (mMeasureAllChildren || child.getVisibility() != GONE) {

            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            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());

            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());

    // 對照 foreground 的最小寬高
    final Drawable drawable = getForeground();
    if (drawable != null) {
        maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
        maxWidth  = Math.max(maxWidth,  drawable.getMinimumWidth());
    }

    // 設定 FrameLayout 自身的測量結果
    setMeasuredDimension(
            resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));

    count = mMatchParentChildren.size();
    if (count > 1) {
        // 有 match_parent 的 child,需要第二輪測量
        for (int i = 0; i < count; i++) {
            final View child = mMatchParentChildren.get(i);
            final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            int childWidthMeasureSpec;
            int childHeightMeasureSpec;

            if (lp.width == LayoutParams.MATCH_PARENT) {
                // parent 已完成測量,child 的 MATCH_PARENT 等同確定性數值
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        getMeasuredWidth()
                        - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                        - lp.leftMargin - lp.rightMargin,
                        MeasureSpec.EXACTLY);
            } else {
                childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                        getPaddingLeftWithForeground() + getPaddingRightWithForeground()
                        + lp.leftMargin + lp.rightMargin,
                        lp.width);
            }

            if (lp.height == LayoutParams.MATCH_PARENT) {
                childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                        getMeasuredHeight()
                        - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                        - lp.topMargin - lp.bottomMargin,
                        MeasureSpec.EXACTLY);
            } else {
                childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        getPaddingTopWithForeground() + getPaddingBottomWithForeground()
                        + lp.topMargin + lp.bottomMargin,
                        lp.height);
            }

            // 用新的 spec 再次測量
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}

這裡揭示了容器測量的一個重要特性:兩輪測量。第一輪先量出容器自身該有多大,第二輪才回頭用確定的尺寸去量那些設為 match_parent 的子元素。這也是為什麼在 ViewGroup 中大量使用 match_parent 會增加測量成本——它可能觸發額外的一整輪遞迴。

六、ViewGroup 的兩個關鍵工具方法

/**
 * 請其中一個子元素測量自己,同時把父容器的 MeasureSpec 需求、
 * padding 與 margins 都考慮進去。child 必須是 MarginLayoutParams。
 * 真正吃重的工作在 getChildMeasureSpec 裡完成。
 */
protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {

    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin + widthUsed,
            lp.width);

    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin + heightUsed,
            lp.height);

    // 若 child 也是 ViewGroup,這裡會實際遞迴下去
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

/**
 * 為某個子元素的某一個維度算出合適的 MeasureSpec。
 *
 * 目標是把「父容器自身的 MeasureSpec」與「子元素的 LayoutParams」這兩份資訊,
 * 組合成最好的結果。舉例來說,如果父容器知道自己的確定大小(mode 為 EXACTLY),
 * 而子元素在 LayoutParams 中表示想跟父容器一樣大,那父容器就應該用一個
 * 精確尺寸去要求子元素配置。
 */
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {

    // 這個方法是協商型的:最終結果可能直接由 spec(parent 提供)決定,
    // 也可能由 childDimension 決定。
    // 所以一個 View 的大小不是單方面決定的,而是一連串條件協商的結果 ——
    // 有時尊重 parent 的 spec,有時堅持自己的 dimension 要求。
    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) {
        // Parent 對我們施加了精確尺寸
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                // child 指定了確定值 → 聽 child 的
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // child 想跟我們一樣大,那就這樣吧
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // child 想自己決定大小,但不能超過我們
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent 對我們施加了最大尺寸限制
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // child 指定了確定值 → 聽 child 的
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // child 想跟我們一樣大,但我們的大小並不固定,只能約束它不超過我們
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent 想看看我們究竟想多大
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // child 指定了確定值,成全它
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
    }

    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

總結:幾個該記住的結論

第一,MeasureSpec 是協商的產物。它由 parent 的 spec 與 child 的 LayoutParams 共同決定。當 parent 是 EXACTLY 而 child 是 wrap_content 時,child 拿到的會是 AT_MOST 加上 parent 的可用大小——這就是 wrap_content 行為如此反直覺的源頭。

第二,measure 走的是一次深度優先遞迴。從 DecorView 出發,每一層容器呼叫 measureChildWithMargins(),進而觸發子 View 的 measure(),最終抵達葉節點。層數越深、子元素越多,測量成本越高,這也是「簡化層級」之所以能優化效能的原因。

第三,自訂 View 有兩條硬性規則:覆寫 onMeasure() 時必須呼叫 setMeasuredDimension();若支援 wrap_content,必須自行計算內容尺寸,不能依賴預設實作。

第四,requestLayout 與 measure 快取有關。若 spec 未變且未標記 FORCE_LAYOUT,measure() 會直接命中快取跳過測量。理解這一點,才能判斷為什麼有些 UI 更新沒有如預期生效。

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