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

解析:繼承 ViewGroup 的子類該如何重寫 onMeasure

編輯:關於 Android 程式設計

自訂 ViewGroup 時,若不處理 onMeasure,子 View 的測量結果往往不如預期。核心觀念其實不複雜:先決定自己有多大,再把父容器給的約束「翻譯」成每個子 View 能理解的 MeasureSpec。

可運行的實作

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
    int measureHeigth = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(measureWidth, measureHeigth);

    for (int i = 0; i < getChildCount(); i++) {
        View v = getChildAt(i);
        Log.v(TAG, "measureWidth is " + v.getMeasuredWidth()
                + " measureHeight is " + v.getMeasuredHeight());

        int widthSpec = 0;
        int heightSpec = 0;
        LayoutParams params = v.getLayoutParams();

        if (params.width > 0) {
            widthSpec = MeasureSpec.makeMeasureSpec(params.width, MeasureSpec.EXACTLY);
        } else if (params.width == -1) {
            widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.EXACTLY);
        } else if (params.width == -2) {
            widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.AT_MOST);
        }

        if (params.height > 0) {
            heightSpec = MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY);
        } else if (params.height == -1) {
            heightSpec = MeasureSpec.makeMeasureSpec(measureHeigth, MeasureSpec.EXACTLY);
        } else if (params.height == -2) {
            heightSpec = MeasureSpec.makeMeasureSpec(measureHeigth, MeasureSpec.AT_MOST);
        }

        v.measure(widthSpec, heightSpec);
    }
}

三種寬度情境的判斷邏輯

關鍵在於讀出 LayoutParams.width 的值,並對應到三種情況:

  • 大於 0:代表布局裡寫的是具體數值,直接用 EXACTLY 建構 MeasureSpec。
  • 等於 -1(MATCH_PARENT):此時不能真的無限延伸,而是取父容器的可用尺寸,一樣用 EXACTLY。
  • 等於 -2(WRAP_CONTENT):用 AT_MOST,把父容器的尺寸當成「上限」傳下去。

高度方向的處理完全對稱。

兩個容易忽略的細節

第一,setMeasuredDimension() 一定要呼叫。少了它,View 的寬高會維持 0,後續排版全部失真。

第二,本文的示範為了簡潔,把 WRAP_CONTENT 直接映射到父容器尺寸,實務上通常還需要搭配 getChildMeasureSpec() 或呼叫 measureChild(),才能正確處理 padding 與群組本身的邊距。上面程式碼中高度 -2 那個分支誤用了 measureWidth,也是這類簡化版本常見的手抄錯誤,實際套用時記得改回 measureHeigth。

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