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

自定義 ViewGroup 最佳入門:繪製流程、onMeasure 與 onLayout 全解析

編輯:關於 Android 程式設計

一、View 的繪製流程

ViewGroup 同樣繼承自 View,所以先看繪製過程依序呼叫了哪些函式。

逐個拆解:

measure() 與 onMeasure()——在 View.java 源碼中:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    ...
    onMeasure(widthMeasureSpec, heightMeasureSpec);
    ...
}

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

measure() 被 final 修飾,無法覆寫;它內部呼叫 onMeasure()。所以自定義 View 時,你要覆寫的是 onMeasure()。layout() 與 onLayout()、draw() 與 onDraw() 也是同樣的配對關係。

dispatchDraw()——在 View 中是空實作,ViewGroup 覆寫了它以便繪製子視圖。自定義 ViewGroup 一般不需要動它。

requestLayout()——佈局需要重新計算時(方向變化、尺寸變化等)呼叫。自定義視圖中若某些情況希望重新測量,要主動呼叫它;它會觸發 measure() 與 layout(),但不會觸發 draw()。

所以自定義 ViewGroup 的核心功課就兩件:

onMeasure():計算子 View 的測量值與模式,並設定自己的寬高
onLayout():為所有子 View 定位

View 樹與遍歷順序

樹的遍歷是有序的,由父到子。每個 ViewGroup 負責測量並配置它的所有子節點,最底層的 View 則只負責測量自己。

measure 階段自上而下,父容器用 getChildMeasureSpec() 依自己的 MeasureSpec 與 padding 算出子 View 的 MeasureSpec:

getChildMeasureSpec(parentHeightMeasure, mPaddingTop + mPaddingBottom, lp.height)

子 View 收到後回呼自己的 measure(),最終透過 setMeasuredDimension() 寫入 mMeasuredWidth 與 mMeasuredHeight。

layout 階段同樣自上而下,計算每個子 View 的 left/top,搭配 measure 階段得到的寬高完成定位:

child.layout(left, top, left + width, top + height)

二、onMeasure 的兩個關鍵類別

measure 過程會為 View 及所有子節點的 mMeasuredWidth、mMeasuredHeight 賦值,之後可用 getMeasuredWidth() 與 getMeasuredHeight() 取得。

ViewGroup.LayoutParams

描述視圖的寬高等參數。呼叫 view.getLayoutParams() 得到的,是其父容器型別對應的 LayoutParams——父容器是 RelativeLayout,拿到的就是 RelativeLayout.LayoutParams。它有三種取值語義:具體數值、MATCH_PARENT(與父容器等寬高,不含 padding)、WRAP_CONTENT(恰好包住內容,含 padding)。

MeasureSpec

測量規格,由「測量模式」與「尺寸」打包成一個 int,共三種模式:

UNSPECIFIED:父容器不施加任何限制,子 View 想多大就多大。ListView、ScrollView 內部會用到,一般自定義 View 碰不到。

EXACTLY:父容器指定了確切尺寸,對應 match_parent 或具體值(如 100dp)。此模式下父容器用 MeasureSpec.getSize() 就能直接知道子 View 該多大。

AT_MOST:父容器給一個上限,對應 wrap_content。此時父容器無法替子 View 決定尺寸,必須由子 View 自己計算——這正是自定義視圖需要實作測量邏輯的場景。

這三個模式的分辨,是自定義 ViewGroup 最容易搞錯的地方。實務上的判斷口訣是:只有在 AT_MOST 時才需要用自己算出的內容尺寸,EXACTLY 時直接採用父容器給的值。

三、onLayout 過程

子視圖的位置一律相對於父視圖而言。View 的 onLayout 是空實作,而 ViewGroup 的 onLayout 是 abstract,所以自定義 ViewGroup 時必須實作它,否則編譯都過不了。

layout 過程中,子 View 會用 getMeasuredWidth()、getMeasuredHeight() 取得 measure 階段的結果作為自己的 width 與 height,然後父容器呼叫每個子 View 的 layout(l, t, r, b) 決定其位置。

四、實作一個 FlowLayout

先看成效:

這裡的核心邏輯是「逐行填裝、超出寬度就換行」。

onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

    int width = 0;       // 最終寬度:取各行寬度的最大值
    int height = 0;      // 最終高度:各行高度累加
    int lineWidth = 0;   // 當前行寬
    int lineHeight = 0;  // 當前行高

    int cCount = getChildCount();
    for (int i = 0; i < cCount; i++) {
        View child = getChildAt(i);
        measureChild(child, widthMeasureSpec, heightMeasureSpec);

        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

        // 再放一個就會超出可用寬度 → 換行
        if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
            width = Math.max(width, lineWidth);
            lineWidth = childWidth;
            height += lineHeight;
            lineHeight = childHeight;
        } else {
            lineWidth += childWidth;
            lineHeight = Math.max(lineHeight, childHeight);
        }

        // 最後一個子 View 收尾
        if (i == cCount - 1) {
            width = Math.max(lineWidth, width);
            height += lineHeight;
        }
    }

    // EXACTLY 用父容器給的值,AT_MOST 用自己的計算結果
    setMeasuredDimension(
        modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(),
        modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop() + getPaddingBottom());
}

onLayout

這裡用了兩個集合:mAllViews 按行分組保存子 View,mLineHeight 記錄每行高度。定位時外層跑行、內層跑該行的每個 View,left 逐個累加,一行結束後 left 歸零、top 加上行高。

private List<List<View>> mAllViews = new ArrayList<>();
private List<Integer> mLineHeight = new ArrayList<>();

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    mAllViews.clear();
    mLineHeight.clear();

    int width = getWidth();
    int lineWidth = 0;
    int lineHeight = 0;
    List<View> lineViews = new ArrayList<>();

    int cCount = getChildCount();
    for (int i = 0; i < cCount; i++) {
        View child = getChildAt(i);
        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        int childWidth = child.getMeasuredWidth();
        int childHeight = child.getMeasuredHeight();

        lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
        lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
        lineViews.add(child);

        if (lineWidth > width - getPaddingLeft() - getPaddingRight()) {
            mLineHeight.add(lineHeight);
            mAllViews.add(lineViews);
            lineWidth = 0;
            lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
            lineViews = new ArrayList<>();
        }
    }
    mLineHeight.add(lineHeight);   // 收尾最後一行
    mAllViews.add(lineViews);

    int left = getPaddingLeft();
    int top = getPaddingTop();
    for (int i = 0; i < mAllViews.size(); i++) {
        lineViews = mAllViews.get(i);
        lineHeight = mLineHeight.get(i);
        for (int j = 0; j < lineViews.size(); j++) {
            View child = lineViews.get(j);
            if (child.getVisibility() == View.GONE) continue;

            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int lc = left + lp.leftMargin;
            int tc = top + lp.topMargin;
            int rc = lc + child.getMeasuredWidth();
            int bc = tc + child.getMeasuredHeight();
            child.layout(lc, tc, rc, bc);
            left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        }
        left = getPaddingLeft();
        top += lineHeight;
    }
}

/** 只需支援 margin,直接沿用系統的 MarginLayoutParams */
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new MarginLayoutParams(getContext(), attrs);
}

使用端

public void initFlowlayout2() {
    for (int i = 0; i < mVals.length; i++) {
        RelativeLayout rl2 = (RelativeLayout) mInflater.inflate(
                R.layout.flow_layout, idFlowlayout2, false);
        ((TextView) rl2.findViewById(R.id.tv)).setText(mVals[i]);
        rl2.setTag(i);
        idFlowlayout2.addView(rl2);
        rl2.setOnClickListener(v -> addViewToFlowlayout1((int) v.getTag()));
    }
}

xml 中要記得把 FlowLayout 的 layout_height 設為 wrap_content,這樣才會走到 AT_MOST 分支、由我們自己算高度;設成 match_parent 的話 onMeasure 會直接採用父容器給的值,自算的邏輯形同白寫。

寫自定義 ViewGroup 時最容易翻車的三處

第一,忘記處理 AT_MOST 分支,導致 wrap_content 下高度塌成 0。第二,onMeasure 與 onLayout 的換行判斷式不一致——兩處的寬度計算必須用同一套公式(含 margin 與 padding),否則會出現「量得出來但擺不進去」的錯位。第三,忘記覆寫 generateLayoutParams,導致子 View 的 margin 完全不生效,因為系統預設給的是不支援 margin 的基類 LayoutParams。

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