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

Android View 繪製機制全解:從 performTraversals 到自定義 ViewGroup

編輯:關於 Android 程式設計

整體流程

整棵 View 樹的繪圖流程由 ViewRoot 的 performTraversals() 發起,它做的事可以概括成三段判斷:是否需要重新計算大小(measure)、是否需要重新安放位置(layout)、是否需要重繪(draw)。

而 invalidate() 與 requestLayout() 則是觸發這條流程的鑰匙:

(流程圖來源:Android 開源專案源碼解析——View 繪製流程)

Measure:把尺寸算出來

  • 為整棵 View 樹計算實際大小,每個 View 的尺寸由父容器與自身共同決定。
  • measure() 是 final 方法,不能覆寫;真正要覆寫的是 onMeasure(),並在其中呼叫 setMeasuredDimension() 設定結果(別忘了把 padding 算進去)。
  • ViewGroup 子類需要在 onMeasure 中遍歷並測量每個子 View。
  • 整個測量過程本質是對 View 樹的遞迴。
  • 測量完成後即可用 getMeasuredWidth() / getMeasuredHeight() 取值。
  • 自定義 ViewGroup 至少需要實作 measure 與 layout 兩個環節。

MeasureSpec 的三種模式

一個 MeasureSpec 由 size 與 mode 組成,並被壓進同一個 int 裡以減少物件配置。三種模式:

  • UNSPECIFIED:父容器不加約束,如 ScrollView、ListView 的內部測量。
  • EXACTLY:父容器指定了確切尺寸,對應 match_parent 或明確 dp 值。
  • AT_MOST:父容器給了上限,子 View 必須在範圍內,對應 wrap_content。

底層是位運算

public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;
    // int 為 32 位,最高 2 位存 mode,其餘 30 位存 size
    private static final int MODE_MASK = 0x3 << MODE_SHIFT;

    public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    public static final int EXACTLY    = 1 << MODE_SHIFT;
    public static final int AT_MOST    = 2 << MODE_SHIFT;

    /** 把 size 與 mode 打包成一個 int */
    public static int makeMeasureSpec(int size, int mode) {
        return size + mode;
    }

    /** 取出 mode */
    public static int getMode(int measureSpec) {
        return (measureSpec & MODE_MASK);
    }

    /** 取出 size */
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }
}

Layout:把位置定下來

  • 決定每個子 View 相對於父容器的位置,注意 margin 與 padding 的影響。
  • ViewGroup 的 onLayout 是抽象方法,子類必須實作;View 的 onLayout 則是空實作。
  • 此時測量已完成,可以安全使用 getMeasuredWidth() / getMeasuredHeight()。
  • 不要在 onDraw 與 onLayout 裡 new 物件——這兩個方法會被高頻呼叫。

LayoutParams:子 View 的說話權

LayoutParams 是 ViewGroup 的內部類,每種 ViewGroup 都有自己的子類,例如 RelativeLayout 對應 RelativeLayout.LayoutParams。getLayoutParams() 拿到的是其父容器類型的 LayoutParams,因此強轉前必須確定實際型別,否則會 ClassCastException。自定義的 margin 等屬性,也應該定義在自己的 LayoutParams 裡。

Draw

  • 自定義 View 覆寫 onDraw()。
  • 自定義 ViewGroup 在 dispatchDraw() 中發起對子 View 的繪製,這個方法不該覆寫。

invalidate 與 requestLayout 的差別

  • invalidate():請求重繪。尺寸不變,不會觸發 layout,只重畫呼叫它的那個 View。若要在子線程刷新,請改用 postInvalidate()。
  • requestLayout():布局將變(方向、尺寸變化)時呼叫,會觸發 measure 與 layout,但不會 draw。

實作一:自定義 View

自定義 View 的邏輯幾乎都在 onDraw,onLayout 通常不用動,onMeasure 要自己處理測量。下面這個範例沒有實際功能,唯一目的是演示 onMeasure 與 onDraw 怎麼寫:

public class CustomView extends View {
    private Paint paint = null;
    private Rect rect = null;
    private int bgColor = Color.parseColor("#673AB7"); // 實務上應抽成自定義屬性
    private int minContentWidth = 50;   // 最小內容寬度,不含 padding
    private int minContentHeight = 50;  // 最小內容高度,不含 padding

    public CustomView(Context context) { this(context, null); }
    public CustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(bgColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            width = getPaddingLeft() + getPaddingRight() + minContentWidth;
            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(width, widthSize);
            }
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;   // 注意:範例原文誤寫成 widthSize
        } else {
            height = getPaddingTop() + getPaddingBottom() + minContentHeight;
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightSize);
            }
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        rect = new Rect(getPaddingLeft(), getPaddingTop(),
                getMeasuredWidth() - getPaddingRight(),
                getMeasuredHeight() - getPaddingBottom());
        canvas.drawRect(rect, paint);
    }
}

實務上這段 onMeasure 可以直接用系統提供的 resolveSize() 或 getDefaultSize() 取代,自己手寫一遍是為了釐清思路。

實作二:自定義 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);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            MyLayoutParams lp = (MyLayoutParams) child.getLayoutParams();
            child.layout(lp.x, lp.y,
                    lp.x + child.getMeasuredWidth(),
                    lp.y + child.getMeasuredHeight());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 0;
        int height = getPaddingTop();
        final int count = getChildCount();

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec); // 必須呼叫
            MyLayoutParams lp = (MyLayoutParams) child.getLayoutParams();

            width = Math.max(width,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);

            lp.x = getPaddingLeft() + lp.leftMargin;
            lp.y = height + lp.topMargin;
            height = height + lp.topMargin + child.getMeasuredHeight() + lp.bottomMargin;
        }

        width = width + getPaddingLeft() + getPaddingRight();
        height = height + getPaddingBottom();

        setMeasuredDimension(
                resolveSize(width, widthMeasureSpec),
                resolveSize(height, heightMeasureSpec));
    }

    // 必須覆寫這三個方法,否則 XML 中的自定義屬性會失效
    @Override
    public MyLayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MyLayoutParams(getContext(), attrs);
    }

    @Override
    protected MyLayoutParams generateDefaultLayoutParams() {
        return new MyLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected MyLayoutParams generateLayoutParams(LayoutParams p) {
        return new MyLayoutParams(p.width, p.height);
    }

    /** 繼承 MarginLayoutParams 才能使用 margin 屬性 */
    public static class MyLayoutParams extends MarginLayoutParams {
        public int x;  // 左邊
        public int y;  // 上邊

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

        public MyLayoutParams(int w, int h) {
            super(w, h);
        }
    }
}

幾個實戰結論

  • 自定義 ViewGroup 忘了覆寫 generateLayoutParams 系列方法,XML 裡寫的 layout_margin 會靜默失效,這是新手最常踩的坑。
  • onMeasure 裡呼叫 measureChild 是必須的,否則子 View 的 getMeasuredWidth() 永遠是 0。
  • onDraw 中避免配置物件、避免呼叫 costly 的運算,這裡是每幀都會跑的路徑。
  • wrap_content 在自定義 View 中預設不會生效,必須自己在 onMeasure 裡處理 AT_MOST 分支,這也是自定义 View 與系統 View 常見的行為差異。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved