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

自訂 ViewGroup 入門:先搞懂 View 與 ViewGroup 的分工

編輯:關於 Android 程式設計

本文整理自鴻洋的自訂 ViewGroup 系列,重點不在程式碼本身,而在把「容器與子元素各負責什麼」這件事想清楚。

需求

做一個 ViewGroup,內部可放入 0 到 4 個子 View,分別依序顯示在左上角、右上角、左下角、右下角。

一、ViewGroup 是什麼

它就是放置 View 的容器。在 XML 版面中,凡是以 layout_ 開頭的屬性都與 ViewGroup 相關,例如 layout_height、layout_width、layout_gravity。它的職責有兩項:

  1. 為子 View 計算出建議的寬、高與測量模式。
  2. 決定子 View 的擺放位置。

注意是「建議」而非「決定」——因為當子 View 的寬高設為 wrap_content 時,只有它自己才算得出實際尺寸。

二、View 是什麼

  1. 依據測量模式與 ViewGroup 給的建議值,算出自己的實際寬高。
  2. 在 ViewGroup 為它指派的區域內繪製自己。

三、三種測量模式

  • EXACTLY:已指定精確值。子 View 設為具體數值或 match_parent 時,父容器會採用這個模式。
  • AT_MOST:有一個尺寸上限。子 View 設為 wrap_content 時對應此模式。
  • UNSPECIFIED:想多大就多大。較少見,主要出現在 AdapterView 的 item 與 ScrollView 的子 View 上。

四、ViewGroup 與 LayoutParams 的關係

為什麼 LinearLayout 的子 View 可以寫 layout_gravity 與 layout_weight,而 RelativeLayout 的子 View 卻有 layout_centerInParent 而沒有前者?

因為每個 ViewGroup 都指定了自己的 LayoutParams 型別,用來宣告「我支援哪些屬性」。翻開 LinearLayout 原始碼,會看到它內部定義了 LinearLayout.LayoutParams,weight 與 gravity 就藏在那裡。

五、從 API 角度看職責劃分

  • View:在 onMeasure 中依傳入的測量值與模式定出自己的寬高,在 onDraw 中完成繪製。
  • ViewGroup:在 onMeasure 中為子 View 傳入測量值與模式,同時也要定出自己的寬高;在 onLayout 中指定各子 View 的位置。

六、程式碼

public class CustomViewGroup extends ViewGroup {

    public CustomViewGroup(Context context) { super(context); }
    public CustomViewGroup(Context context, AttributeSet attrs) { super(context, attrs); }
    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /** 一、指定 LayoutParams 為 MarginLayoutParams */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /** 二、計算所有子 View 尺寸,據此設定自己的寬高 */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 1. 取得上級容器推薦的寬高與計算模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        // 2. 讓所有子 View 自我測量
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        // 3. wrap_content 時依子 View 尺寸自行計算
        int width = 0;
        int height = 0;
        int cCount = getChildCount();
        int lHeight = 0; // 左側兩個子 View 的高度總和
        int rHeight = 0; // 右側兩個子 View 的高度總和
        int tWidth = 0;  // 上方兩個子 View 的寬度總和
        int bWidth = 0;  // 下方兩個子 View 的寬度總和

        for (int i = 0; i < cCount; i++) {
            View childView = getChildAt(i);
            int cWidth = childView.getMeasuredWidth();
            int cHeight = childView.getMeasuredHeight();
            MarginLayoutParams cParams = (MarginLayoutParams) childView.getLayoutParams();

            if (i == 0 || i == 1) {
                tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
            }
            if (i == 2 || i == 3) {
                bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
            }
            if (i == 0 || i == 2) {
                lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
            }
            if (i == 1 || i == 3) {
                rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
            }
        }
        width = Math.max(tWidth, bWidth);
        height = Math.max(lHeight, rHeight);

        // 4. 非 wrap_content 則直接採用父容器的計算值
        setMeasuredDimension(
                (widthMode == MeasureSpec.EXACTLY) ? sizeWidth : width,
                (heightMode == MeasureSpec.EXACTLY) ? sizeHeight : height);
    }

    /** 三、為每個子 View 定位 */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            View childView = getChildAt(i);
            int cWidth = childView.getMeasuredWidth();
            int cHeight = childView.getMeasuredHeight();
            MarginLayoutParams cParams = (MarginLayoutParams) childView.getLayoutParams();

            int cl = 0, ct = 0, cr = 0, cb = 0;
            switch (i) {
                case 0: // 左上
                    cl = cParams.leftMargin;
                    ct = cParams.topMargin;
                    break;
                case 1: // 右上
                    cl = getWidth() - cWidth - cParams.leftMargin - cParams.rightMargin;
                    ct = cParams.topMargin;
                    break;
                case 2: // 左下
                    cl = cParams.leftMargin;
                    ct = getHeight() - cHeight - cParams.topMargin - cParams.bottomMargin;
                    break;
                case 3: // 右下
                    cl = getWidth() - cWidth - cParams.leftMargin - cParams.rightMargin;
                    ct = getHeight() - cHeight - cParams.topMargin - cParams.bottomMargin;
                    break;
            }
            cr = cl + cWidth;
            cb = ct + cHeight;
            childView.layout(cl, ct, cr, cb);
        }
    }
}

七、三種版面情境

同一個 CustomViewGroup,只改根節點的寬高屬性,就會呈現完全不同的效果。

情境一,固定 200dp × 200dp,四個 50dp 的方塊各據一角:

<com.cctvjiatao.customviewgroup.view.CustomViewGroup
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="#AA333333">
    <TextView android:layout_width="50dp" android:layout_height="50dp"
        android:background="#FF4444" android:gravity="center"
        android:text="0" android:textColor="#FFFFFF" android:textSize="22sp" />
    <TextView android:layout_width="50dp" android:layout_height="50dp"
        android:background="#00ff00" android:gravity="center"
        android:text="1" android:textColor="#FFFFFF" android:textSize="22sp" />
    <TextView android:layout_width="50dp" android:layout_height="50dp"
        android:background="#ff0000" android:gravity="center"
        android:text="2" android:textColor="#FFFFFF" android:textSize="22sp" />
    <TextView android:layout_width="50dp" android:layout_height="50dp"
        android:background="#0000ff" android:gravity="center"
        android:text="3" android:textColor="#FFFFFF" android:textSize="22sp" />
</com.cctvjiatao.customviewgroup.view.CustomViewGroup>

情境二,根節點改成 wrap_content,並把第 0 個子 View 放大到 150dp。此時容器會依子元素內容收縮,正好驗證了 onMeasure 裡那段自行計算高度與寬度的邏輯是否正確。

情境三,根節點設為 match_parent,並讓對角線上的兩個子 View(第 0 與第 3 個)都放大到 150dp。這能測試「左右兩側高度總和取最大值」的算法在數字不對稱時是否仍然正確。

這三個情境合起來,其實就是一份自測清單:分別驗證 EXACTLY 與 AT_MOST 兩種測量模式,以及 margin 與不對稱尺寸下的定位正確性。

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