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

【例證】getWidth() 與 getMeasuredWidth() 到底差在哪

編輯:關於 Android 程式設計

一個起點

在自訂 View 的 onDraw() 裡畫一個圓:

oval.left   = getMeasuredWidth()  / 2 - radius;
oval.top    = getMeasuredHeight() / 2 - radius;
oval.right  = getMeasuredWidth()  / 2 + radius;
oval.bottom = getMeasuredHeight() / 2 + radius;
canvas.drawArc(oval, 0, 360, true, mPaint);

這樣寫沒問題。但心裡會有個疑問:為什麼不用 getWidth()、getHeight()? 大部分情況下兩者結果一樣,那差異究竟在哪?與其看網路上各種說法,不如自己從原始碼扣一次。

View#getMeasuredWidth()

public final int getMeasuredWidth() {
    return mMeasuredWidth & MEASURED_SIZE_MASK;
}

它回傳的是最近一次 measure() 之後記錄下來的寬度。順著原始碼看:

自訂 View 常覆寫 onMeasure():

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

setMeasuredDimension() 最後會走到 setMeasuredDimensionRaw():

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;
    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

前两行的赋值,就是 getMeasuredWidth()/getMeasuredHeight() 的來源。

所以當你在 onMeasure() 裡直接寫 setMeasuredDimension(200, 300),getMeasuredWidth() 必然是 200、getMeasuredHeight() 必然是 300。實務上当然不会写死,而是先解析 widthMeasureSpec 再傳進去。

什麼時候必須覆寫 onMeasure?

因為自訂 View 在屬性為 wrap_content 時,若不做處理,實際表現會等同 match_parent。原因在於:

當父容器的 specMode 為 EXACTLY 或 AT_MOST 時,子 View 不論宣告 wrap_content 還是 match_parent,預設尺寸都是父容器的大小 parentSize。

實測看看。自訂 View 設為 match_parent:

改為 wrap_content:

兩者完全一樣。對照一下明確給 40dp 的情形:

差異就很明顯了。除非是精確值,否則尺寸一律等於父容器。

這不能接受——我希望 wrap_content 時有一個預設大小 200×200,於是有了:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int speSize = MeasureSpec.getSize(heightMeasureSpec);
    int speMode = MeasureSpec.getMode(heightMeasureSpec);

    if (speMode == MeasureSpec.AT_MOST) {
        // wrap_content:給一個自訂的預設尺寸
        setMeasuredDimension(100, 100);
    } else {
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }
}

這就是我們覆寫 onMeasure 的主要理由:讓 wrap_content 能依需求自行收斂。

View#getWidth()

@ViewDebug.ExportedProperty(category = "layout")
public final int getWidth() {
    return mRight - mLeft;
}

mLeft 與 mRight 是 layout 流程傳入的四個參數中的兩個:

public void layout(int l, int t, int r, int b) {
    ...
    boolean changed = isLayoutModeOptical(mParent)
            ? setOpticalFrame(l, t, r, b)
            : setFrame(l, t, r, b);
    ...
}

不論走 setOpticalFrame 還是 setFrame,最終都會在 setFrame 中完成賦值:

protected boolean setFrame(int left, int top, int right, int bottom) {
    boolean changed = false;
    if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
        changed = true;
        mLeft = left;
        mTop = top;
        mRight = right;
        mBottom = bottom;
    }
    return changed;
}

所以 getWidth() 反映的是 layout 階段決定的實際位置與尺寸,而不是測量值。

兩者何時會不一致?

當你繼承 ViewGroup 並在 onLayout() 中手動指定子 View 的位置時。

實作一個簡單的換行排列:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int mViewGroupWidth = getMeasuredWidth();  // 容器總寬
    int mPainterPosX = l;                     // 繪圖游標橫座標
    int mPainterPosY = t;                     // 繪圖游標縱座標
    int childCount = getChildCount();

    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        int width = childView.getMeasuredWidth();
        int height = childView.getMeasuredHeight();

        // 剩餘空間不足則換行
        if (mPainterPosX + width > mViewGroupWidth) {
            mPainterPosX = l;
            mPainterPosY += height;
        }

        childView.layout(mPainterPosX, mPainterPosY,
                         mPainterPosX + width, mPainterPosY + height);

        mPainterPosX += width;
    }
}

如果把 layout 寫死成固定值:

childView.layout(0, 0, 100, 200);

版面如下:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.user.mytestview.myviewgroup
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.example.user.mytestview.myview
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </com.example.user.mytestview.myviewgroup>
</RelativeLayout>

在子 View 打 Log:

這時 getWidth() 是 100,而 getMeasuredWidth() 仍是測量出來的值,兩者不再相等。

結論:該用哪一個?

View 的處理順序是 onMeasure() → onLayout() → onDraw()(可參考 ViewRootImpl#performTraversals())。因此:

  • 在 onMeasure() 及其之後、layout 完成之前,用 getMeasuredWidth(),因為此時 layout 尚未發生,getWidth() 拿到的會是舊值甚至 0。
  • 在 onLayout() 之後(例如 onDraw() 中),用 getWidth() 更能反映最終呈現在畫面上的實際尺寸。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved