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

繼承 ViewGroup 必讀:onMeasure、onLayout 與 MeasureSpec 完全解析

編輯:Android 開發教學

自定義 ViewGroup 時,有兩個方法一定要覆寫:onMeasure() 與 onLayout()。它們的分工、參數含義與眉角,一次講清楚。

一、onMeasure 中的兩件必做事

1. 呼叫 setMeasuredDimension 保存測量結果
void android.view.View.setMeasuredDimension(int measuredWidth, int measuredHeight)
在 onMeasure(int, int) 中,必須呼叫這個方法來儲存測量出的寬高;不做會直接觸發 IllegalStateException。

2. 對子 View 呼叫 measure
void android.view.View.measure(int widthMeasureSpec, int heightMeasureSpec)
這個方法用來測量 view 的大小。父 view 透過 width 與 height 兩個參數提供 constraint 資訊,而實際的測量工作在 onMeasure(int, int) 中完成。因此只有 onMeasure 可以且必須被覆寫。

二、onMeasure 解析

void android.view.View.onMeasure(int widthMeasureSpec, int heightMeasureSpec)
測量 view 及其內容以決定寬高。這個方法由 measure(int, int) 呼叫,必須被覆寫才能準確有效地測量內容。覆寫時必須呼叫 setMeasuredDimension(int, int) 儲存結果,否則會拋出 IllegalStateException;呼叫父類別的 onMeasure 也是合法做法。

View 的預設測量結果取自背景尺寸,除非允許更大的尺寸。子 view 必須覆寫 onMeasure 才能提供更精確的測量值;若覆寫,還要確保測出的寬高至少不低於 getSuggestedMinimumHeight() 與 getSuggestedMinimumWidth() 回傳的最小值。

三、onLayout 解析

void android.view.ViewGroup.onLayout(boolean changed, int l, int t, int r, int b)
在 view 為子 view 設定尺寸與位置時呼叫。子 view(包括自己的子層級)必須覆寫此方法,並呼叫各自的 layout(int, int, int, int)。

參數含義:changed 表示 view 是否有新的尺寸或位置;l 是相對父 view 的左側位置;t 是頂部位置;r 是右側;b 是底部。

四、View.MeasureSpec

android.view.View.MeasureSpec 封裝了布局規格,並由父 view 傳遞給子 view。每個 MeasureSpec 代表寬或高的規格,內部包含一個 size 與一個 mode。mode 有三種取值:

  • UNSPECIFIED(1073741824,0x40000000):未加規定,父層沒有對子 view 施加任何限制。
  • EXACTLY(0,0x0):精確值,父 view 已為子 view 確定精確尺寸。
  • AT_MOST(-2147483648,0x80000000):最大值,子 view 可以在指定尺寸內盡量大。

五、完整範例:垂直排列的自定義 ViewGroup

第一步,自定義一個繼承 ViewGroup 的容器:

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class MyViewGroup extends ViewGroup {

    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /** 計算控件的大小 */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int measureWidth = measureWidth(widthMeasureSpec);
        int measureHeight = measureHeight(heightMeasureSpec);

        // 計算自定義 ViewGroup 中所有子控件的大小
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        // 設定自定義控件 MyViewGroup 的大小
        setMeasuredDimension(measureWidth, measureHeight);
    }

    private int measureWidth(int pWidthMeasureSpec) {
        int result = 0;
        int widthMode = MeasureSpec.getMode(pWidthMeasureSpec); // 得到模式
        int widthSize = MeasureSpec.getSize(pWidthMeasureSpec); // 得到尺寸

        switch (widthMode) {
            /**
             * mode 共有三種情況:MeasureSpec.UNSPECIFIED、MeasureSpec.EXACTLY、
             * MeasureSpec.AT_MOST。
             *
             * MeasureSpec.EXACTLY 是精確尺寸。當 layout_width 指定為具體數值
             * (如 android:layout_width="50dip")或 FILL_PARENT 時,控件大小已確定。
             *
             * MeasureSpec.AT_MOST 是最大尺寸。當 layout_width 指定為 WRAP_CONTENT 時,
             * 控件大小隨子空間或內容變化,只要不超過父控件允許的最大尺寸即可。
             *
             * MeasureSpec.UNSPECIFIED 是未指定尺寸,這種情況不多,通常是父控件為
             * AdapterView,透過 measure 方法傳入的模式。
             */
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = widthSize;
                break;
        }
        return result;
    }

    private int measureHeight(int pHeightMeasureSpec) {
        int result = 0;
        int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);

        switch (heightMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = heightSize;
                break;
        }
        return result;
    }

    /**
     * 覆寫 onLayout 的目的是指定視圖的顯示位置。它在 onMeasure 之後執行——
     * 視圖只有先知道大小,才能決定怎麼擺放。
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int mTotalHeight = 0; // 記錄總高度
        int childCount = getChildCount();

        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            // 取得 onMeasure 中計算出的視圖尺寸
            int measureHeight = childView.getMeasuredHeight();
            int measuredWidth = childView.getMeasuredWidth();

            childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight);
            mTotalHeight += measureHeight; // 往下堆疊
        }
    }
}

第二步,布局檔:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00f0f0"
    tools:context=".MainActivity" >

    <net.loonggg.viewgroup.MyViewGroup
        android:id="@+id/myViewGroup"
        android:layout_width="480dp"
        android:layout_height="300dp"
        android:background="#0f0f0f" >

        <TextView
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:background="#000000"
            android:gravity="center"
            android:text="第一個TextView" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="200dp"
            android:background="#ffffff"
            android:gravity="center"
            android:text="第二個TextView" />
    </net.loonggg.viewgroup.MyViewGroup>
</RelativeLayout>

這個範例刻意簡化:measureWidth 與 measureHeight 直接把父層給的 size 當成自己的尺寸,onLayout 則用一個累加變數 mTotalHeight 把子 View 由上往下依序排開。真要 production 使用,還得補上 UNSPECIFIED 分支的處理、wrap_content 時依子 View 內容自行計算,以及 padding 與 margin 的計算。

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