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

自定義 ViewGroup 完整教學:從 onMeasure 到 onLayout 手寫一個容器

編輯:關於 Android 程式設計

前面我們已經看過幾種自定義控件的做法:音頻條,以及可複用的組合控件。還沒看過的建議先補上,因為本篇會直接沿用其中的成果。

今天要往下一層走:自己寫一個 ViewGroup。

一、先釐清兩個問題

1. 什麼是 ViewGroup?

ViewGroup 是一種容器,可以包含零個或多個 View 與子 ViewGroup。

2. ViewGroup 有什麼作用?

它負責存放與管理子控件,並依自己的測量模式去測量子 View、決定子 View 的位置。這兩件事分別對應兩個方法:onMeasure() 管大小,onLayout() 管位置。接下來就從這兩個方法著手。

二、繼承 ViewGroup

一如往常,先繼承並把三個建構子補齊:

public class CustomViewGroup extends ViewGroup {

    public CustomViewGroup(Context context) {
        this(context, null);
    }

    public CustomViewGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

三、重寫 onMeasure:測量子 View

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        measureChild(children, widthMeasureSpec, heightMeasureSpec);
    }
}

寫法很直白:先取得子 View 數量,逐一取出,再呼叫 measureChild() 測量。注意這裡把父容器自己的 widthMeasureSpec、heightMeasureSpec 一起傳進去了——因為子 View 的測量結果,本來就取決於父容器提供的測量模式。

3.1 measureChild() 原始碼

protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();

    final int childWidthMeasureSpec = getChildMeasureSpec(
            parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight,
            lp.width);

    final int childHeightMeasureSpec = getChildMeasureSpec(
            parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom,
            lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

它先取得子 View 的 LayoutParams,再把「父容器的測量規格 + 自己的 padding + 子 View 的寬高參數」一起交給 getChildMeasureSpec() 換算出子 View 的測量規格。由此可得第一個結論:子 View 的大小 = 父容器的測量模式 + 子 View 的 LayoutParams + 父容器的 padding。

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

        // 父容器不限大小,讓子 View 自己決定
        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);
}

邏輯是兩層判斷:先扣掉 padding 得到可用大小 size,再依父容器的 specMode(EXACTLY / AT_MOST / UNSPECIFIED)分別判斷子 View 的 childDimension(明確數值 / MATCH_PARENT / WRAP_CONTENT),最後組回一組新的 MeasureSpec。知道了子 View 的測量模式與大小,它該有多大就確定了。

四、重寫 onLayout:決定子 View 位置

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childCount = getChildCount();
    int preHeight = 0;
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        int cHeight = children.getMeasuredHeight();
        if (children.getVisibility() != View.GONE) {
            children.layout(l, preHeight, r, preHeight += cHeight);
        }
    }
}

先取得子 View 數量並逐一走訪,然後用一個變數 preHeight 記錄「到目前為止累積的高度」,每個子 View 就從這個高度開始往下排。這樣就達到了垂直依次排列的效果。

值得注意的是,View 的 layout() 本身並沒有硬性規定怎麼排:

public void layout(int l, int t, int r, int b) {
    if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
        onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
        mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
    }

    int oldL = mLeft;
    int oldT = mTop;
    int oldB = mBottom;
    int oldR = mRight;

    boolean changed = isLayoutModeOptical(mParent)
            ? setOpticalFrame(l, t, r, b)
            : setFrame(l, t, r, b);

    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
        onLayout(changed, l, t, r, b);
        mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnLayoutChangeListeners != null) {
            ArrayList<OnLayoutChangeListener> listenersCopy =
                    (ArrayList<OnLayoutChangeListener>) li.mOnLayoutChangeListeners.clone();
            int numListeners = listenersCopy.size();
            for (int i = 0; i < numListeners; ++i) {
                listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
            }
        }
    }

    mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
    mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}

關鍵是 setFrame(l, t, r, b)(決定四個邊界座標),而真正的定位邏輯被交給 onLayout(changed, l, t, r, b)。而 ViewGroup 裡的這個方法:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

是空的。換句話說,系統把最大的自由度留給了我們——排法完全自訂。

五、看看成果

拿前面寫過的自定義 View 當子 View 來試試。

custom_viewgroup.xml:

<?xml version="1.0" encoding="utf-8"?>
<com.sanhuimusic.mycustomview.view.CustomViewGroup
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    android:id="@+id/customViewGroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#999999">

    <com.sanhuimusic.mycustomview.view.CompositeViews
        android:id="@+id/topBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#999999"
        custom:titleText="@string/titleText"
        custom:titleColor="#000000"
        custom:titleTextSize="@dimen/titleTextSize"
        custom:titleBackground="#999999"
        custom:leftText="@string/leftText"
        custom:leftTextColor="#FFFFFF"
        custom:leftBackground="#666666"
        custom:leftTextSize="@dimen/leftTextSize"
        custom:rightText="@string/rightText"
        custom:rightTextColor="#FFFFFF"
        custom:rightBackground="#666666"
        custom:rightTextSize="@dimen/rightTextSize" />

    <com.sanhuimusic.mycustomview.view.AudioBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</com.sanhuimusic.mycustomview.view.CustomViewGroup>

MainActivity:

public class MainActivity extends AppCompatActivity {

    private CompositeViews topBar;
    private Context mContext;
    private CustomViewGroup mViewGroupContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_viewgroup);
        mContext = this;
        init();
    }

    private void init() {
        mViewGroupContainer = (CustomViewGroup) findViewById(R.id.customViewGroup);
        topBar = (CompositeViews) findViewById(R.id.topBar);

        topBar.setOnTopBarClickListener(new CompositeViews.TopBarClickListener() {
            @Override
            public void leftClickListener() {
                ToastUtil.makeText(MainActivity.this, "您點擊了返回鍵", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void rightClickListener() {
                ToastUtil.makeText(MainActivity.this, "您點擊了搜尋鍵", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

子 View 確實垂直排列下來了。但馬上會想到一個問題:前面在寫自定義 View 時提過,wrap_content 需要特別處理才能正確生效——自定義 ViewGroup 也是同樣的道理。試著把 CustomViewGroup 的寬高改成 wrap_content,果然不支援。

所以自定義 ViewGroup 有兩件事一定要處理:

  1. 支援 wrap_content 情境下的測量。
  2. 支援自身的 padding 屬性。

六、讓它支援 wrap_content

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();

    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        measureChild(children, widthMeasureSpec, heightMeasureSpec);
    }

    /** 讓它支援自身的 wrap_content */
    int widthSpecMode  = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize  = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

    int mWidth = 0;
    int mHeight = 0;
    int mMaxWidth = 0;

    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        // 寬高都是 wrap_content:累加子 View 的寬高
        for (int i = 0; i < childCount; i++) {
            View children = getChildAt(i);
            mWidth  += children.getMeasuredWidth();
            mHeight += children.getMeasuredHeight();
        }
        setMeasuredDimension(mWidth, mHeight);

    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        // 只有寬是 wrap_content:取子 View 最大寬
        for (int i = 0; i < childCount; i++) {
            View children = getChildAt(i);
            mMaxWidth = Math.max(mMaxWidth, children.getMeasuredWidth());
        }
        setMeasuredDimension(mMaxWidth, heightSpecSize);

    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        // 只有高是 wrap_content:累加子 View 高度
        for (int i = 0; i < childCount; i++) {
            View children = getChildAt(i);
            mHeight += children.getMeasuredHeight();
        }
        setMeasuredDimension(widthSpecSize, mHeight);
    }
}

核心觀念:自定義 ViewGroup 若不呼叫 setMeasuredDimension(),系統會回傳一個未初始化的尺寸,畫面就全亂了。這裡分三種情況處理:

  • 寬高皆為 wrap_content:分別累加子 View 的寬與高,再 setMeasuredDimension。
  • 僅寬為 wrap_content:取子 View 最大寬,高度沿用父容器規格。
  • 僅高為 wrap_content:累加子 View 高度,寬度沿用父容器規格。

七、支援自身的 padding

先取出四邊 padding:

leftPadding   = getPaddingLeft();
topPadding    = getPaddingTop();
rightPadding  = getPaddingRight();
bottomPadding = getPaddingBottom();

在計算尺寸時把它們加回去:

if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        mWidth  += children.getMeasuredWidth();
        mHeight += children.getMeasuredHeight();
    }
    setMeasuredDimension(mWidth + leftPadding + rightPadding,
                         mHeight + topPadding + bottomPadding);

} else if (widthSpecMode == MeasureSpec.AT_MOST) {
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        mMaxWidth = Math.max(mMaxWidth, children.getMeasuredWidth());
    }
    setMeasuredDimension(mMaxWidth + leftPadding + rightPadding,
                         heightSpecSize + topPadding + bottomPadding);

} else if (heightSpecMode == MeasureSpec.AT_MOST) {
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        mHeight += children.getMeasuredHeight();
    }
    setMeasuredDimension(widthSpecSize + leftPadding + rightPadding,
                         mHeight + topPadding + bottomPadding);
}

定位時同樣要納入 padding:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childCount = getChildCount();
    int preHeight = topPadding;     // 不再從 0 開始
    for (int i = 0; i < childCount; i++) {
        View children = getChildAt(i);
        int cHeight = children.getMeasuredHeight();
        if (children.getVisibility() != View.GONE) {
            children.layout(l + leftPadding,
                            preHeight,
                            r + rightPadding,
                            preHeight += cHeight);
        }
    }
}

八、還有什麼該補的

除了上述兩點,實務上通常還會處理:

  • 子 View 的 margin:思路與 padding 類似,但要在 LayoutParams 中覆寫 generateLayoutParams() 並讀取 MarginLayoutParams。
  • generateDefaultLayoutParams():不覆寫的話,子 View 的 layout_width="match_parent" 等屬性可能拿不到正確的 LayoutParams。
  • 交錯或網格排列:在 onMeasure 中記錄每個子 View 的位置,於 onLayout 中依序擺放。

自定義 ViewGroup 明顯比自定義 View 複雜,因為你要同時對「測量」與「排版」兩套流程負責。但拆解下來其實就是固定套路:onMeasure 決定自己多大、順便量好每個孩子;onLayout 決定每個孩子擺在哪。把這兩句話吃透,剩下的排列邏輯都只是這兩步的變形。

另外別忘了,本篇只處理了 UI 顯示,功能與事件(例如攔截滑動手勢)是另一個主題,可以後續再補。

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