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

自定義 View 系列(二):onMeasure 源碼逐行拆解與 wrap_content 正解

編輯:關於 Android 程式設計

自定義 View 的三步曲是 measure、layout、draw,而 measure 站在整條鏈路的最前端。偏偏這一步最容易被讀懂個皮毛就跳過:為什麼父 View 會決定子 View 的 MeasureSpec?為什麼自己寫的 View 在 XML 裡寫 wrap_content,跑出來卻像 match_parent?本文就從源碼把這件事講到底。


MeasureSpec:父子之間的那份契約

系統要畫出一個 View,得先知道它多寬多高,這個「詢問與回答」的過程就是測量,而 MeasureSpec 貫穿其中。

官方文件的說法很精簡:

A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode.

從這段話可以抽出三個要點:MeasureSpec 封裝了父容器傳給子 View 的版面要求;它分別描述寬與高;它由 size 與 mode 兩部分組成。

它本質上是一個 32 位元的 int:高 2 位是 SpecMode,低 30 位是 SpecSize。

int specSize = MeasureSpec.getSize(measureSpec);
int specMode = MeasureSpec.getMode(measureSpec);
int measureSpec = MeasureSpec.makeMeasureSpec(size, mode);

三種模式的意思

  • EXACTLY:父容器已經確定子 View 的精確大小,子 View 就得照這個尺寸走,測量結果即 specSize。
  • AT_MOST:父容器給不精確答案,只指定一個上限 specSize,子 View 的測量結果不得超過它。
  • UNSPECIFIED:父容器完全不限制。這模式主要出現在系統內部,或 ListView、ScrollView 這類滑動容器,實務上很少自己處理。

子 View 的 MeasureSpec 是怎麼生出來的

ViewGroup 測量子 View 時會走 measureChildWithMargins():

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.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

注意它的參數:父容器的 MeasureSpec、父容器在水平與垂直方向已被佔用的空間。父 View 的資訊竟然出現在「量子 View」的方法簽名裡,這已經暗示了答案——子 View 的 MeasureSpec 由父容器的 MeasureSpec 與子 View 自己的 LayoutParams 共同決定。

其中 padding 參數的組成值得細看:mPaddingLeft + mPaddingRight 是父容器左右內距,lp.leftMargin + lp.rightMargin 是子 View 左右外距,這四段空間都無法再拿來排版子 View,加總即為「父容器在水平方向已被佔用的空間」;垂直方向同理。

getChildMeasureSpec:真正的決策點

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);
    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 if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

關鍵是 childDimension >= 0 這個判斷。之所以可能為負,是因為 MATCH_PARENT = -1、WRAP_CONTENT = -2;也就是說,大於等於 0 代表使用者寫了一個具體數值,例如 100px。

一張表講完所有組合

父容器 specMode子 View 的 LayoutParams子 View 的 specMode子 View 的 specSize
EXACTLY具體數值EXACTLYchildDimension
EXACTLYmatch_parentEXACTLYsize(父容器剩餘空間)
EXACTLYwrap_contentAT_MOSTsize(父容器剩餘空間)
AT_MOST具體數值EXACTLYchildDimension
AT_MOSTmatch_parentAT_MOSTsize(父容器剩餘空間)
AT_MOSTwrap_contentAT_MOSTsize(父容器剩餘空間)
UNSPECIFIED具體數值EXACTLYchildDimension
UNSPECIFIEDmatch_parent / wrap_contentUNSPECIFIED0(或 size)

 

用白話再說一次:只要子 View 寫了具體 px 值,不論父容器是什麼模式,結果一律是 EXACTLY 加上那個數字;寫 match_parent 時,子 View 會「複製」父容器的模式;寫 wrap_content 時,結果幾乎一定是 AT_MOST 加上父容器剩餘空間。

另外要記住:這裡算出來的只是系統給的「參考值」。你也可以完全跳過這套流程,直接在 onMeasure 裡呼叫 setMeasuredDimension() 指定測量結果。

onMeasure 的源碼鏈路

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

呼叫順序是:onMeasure → setMeasuredDimension,中間透過 getDefaultSize 取得寬高,而 getDefaultSize 的第一個參數來自 getSuggestedMinimumWidth / getSuggestedMinimumHeight。

getSuggestedMinimumWidth

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

沒有背景時,最小值就是 mMinWidth,可透過 XML 的 minWidth 或 setMinimumWidth() 設定;有背景時,取 mMinWidth 與背景最小寬度的較大者。getSuggestedMinimumHeight 邏輯相同。

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;
}

除了罕見的 UNSPECIFIED,其餘情況回傳的都是 specSize。換句話說:在 measure 階段,View 的寬高由 MeasureSpec 中的 specSize 決定。

setMeasuredDimension

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;
    mPrivateFlags |= MEASURED_DIMENSION_SET;
}

wrap_content 的陷阱

把上面的結論擺在一起看,問題就浮現了:當子 View 寫 wrap_content,不論父容器是 AT_MOST 還是 EXACTLY,系統給它的 specMode 都是 AT_MOST、specSize 都是父容器剩餘空間。再對照 getDefaultSize,AT_MOST 直接回傳 specSize——於是 wrap_content 的行為等同於 match_parent。

所以自定義 View 若希望 wrap_content 真的「包裹內容」,必須在 onMeasure 中自行攔截處理。

自定義 onMeasure 的正確寫法

分兩種情況:寬高都是 wrap_content 時,兩者都用自己的預設值 mWidth、mHeight;只有一邊是 wrap_content 時,那邊用預設值,另一邊沿用系統測得的 specSize。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, mHeight);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, mHeight);
    }
}

先呼叫 super.onMeasure() 保留系統測量結果,再針對 AT_MOST 分支覆寫。mWidth 與 mHeight 是預設值,可依實際內容決定,例如 TextView 就是用文字測出的內容尺寸來處理這件事。

那 match_parent 搭配 AT_MOST 呢?

仔心包對照會發現一個疑慮:如果子 View 寫 match_parent 而父容器是 AT_MOST,子 View 也會拿到 AT_MOST,照上面的判斷邏輯豈不是會被改成預設值?原本要撐滿父容器,結果變成固定尺寸。

要出現「父容器為 AT_MOST」,只有兩條路:父容器自己是 wrap_content,或父容器是 match_parent 而其上層為 AT_MOST。

第一條路本身就矛盾:父容器要包裹內容,子 View 卻要跟父容器一樣大,誰也決定不了誰,這是邏輯上不合理、實務上不該出現的寫法。

第二條路往上追一層:爺容器不可能是 wrap_content(同前);也不可能是具體數值,因為那樣 specMode 會是 EXACTLY,與前提衝突;只能是 match_parent。而若爺容器是 match_parent 且 EXACTLY,父容器就該是 EXACTLY,同樣衝突;只剩爺容器為 match_parent + AT_MOST 這一條,於是又回到同樣的循環,一路推到根 View——但根 View 若是 match_parent,其 specMode 必為 EXACTLY,循環在此斷掉,依然矛盾。

結論:圖中紅色標記的那格,本身就是不可能穩定成立的組合,等價於第一條路的錯誤寫法。真正需要特別處理的,只有 wrap_content 那一格;而「從根到父容器一路 wrap_content、子 View 也是 wrap_content」正是我們上面補強的情況。


把 MeasureSpec 與 measure 的原理吃透,後續讀 layout 與 draw 才不會卡住。下一篇:layout。

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