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

Android 自定義 View 入門:從 onMeasure 到 onDraw 的完整實踐

編輯:關於 Android 程式設計

對不少剛入門的 Android 開發者來說,「自定義 View」幾乎是一道心理門檻;但如果你想在職業發展上再往上走一層,這又是繞不開的必修課。本文先把整體思路梳理清楚,再用一個可運行的例子把流程走一遍。

自定義 View 的四個基本步驟

無論要做什麼樣的效果,自定義 View 的骨架大致都是這四步:

1、定義自定義屬性;
2、在構造方法中讀取這些屬性;
3、重寫 onMeasure(視需求而定,並非強制);
4、重寫 onDraw 完成繪製。

我把第三步用括號標了出來,是因為很多簡單場景下沿用系統的測量邏輯就夠用了。前兩步在之前的《Android 自定義屬性》一文裡已經講得比較細,這裡把重點放在第三、第四步。

onMeasure:視圖大小的測量過程

onMeasure() 顧名思義就是「測量尺寸」。它接收 widthMeasureSpec 與 heightMeasureSpec 兩個參數,分別決定視圖的寬與高的規格與大小。

每一個 MeasureSpec 都由兩部分打包而成:specSize 記錄具體大小,specMode 記錄測量規格。specMode 共有三種:

EXACTLY

表示父視圖已經為子視圖確定了精確尺寸,子視圖最終大小就應該是 specSize。這通常在布局中寫死了具體數值,或使用 MATCH_PARENT 時出現。

AT_MOST

表示子視圖的大小不能超過 specSize,開發者應在這個上限之內盡量貼合內容。對應布局中的 WRAP_CONTENT。

UNSPECIFIED

表示父視圖不施加任何限制,子視圖想多大就多大。這種情況相對少見,一般出現在 ScrollView 之類的容器裡。

那 widthMeasureSpec 和 heightMeasureSpec 從哪裡來?通常都是父視圖計算之後傳遞給子視圖的,也就是說父容器會在一定程度上參與決定子視圖的尺寸。

既然 onMeasure 可以重寫,就意味着你能完全接管測量邏輯。比如無視布局文件,把尺寸固定成 200×200:

public class MyView extends View {
    // ...省略其他構造方法
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(200, 200);
    }
}

這樣一來,不管 XML 裡寫的是多少 dp,MyView 最終呈現出來的都是 200×200 像素。

這裡有個容易踩的坑:只有在調用過 setMeasuredDimension() 之後,getMeasuredWidth() 和 getMeasuredHeight() 才有值,之前調用一律返回 0。另外要注意區分 getWidth()/getHeight(),它們要等 ViewGroup 的 onLayout() 流程走完才能取到有效值。

小結一下:視圖尺寸其實是三方博弈的結果——父容器提供參考值,開發者在 XML 中表達期望,而視圖自己在 onMeasure 裡做最終裁決。

onDraw:真正開始畫東西

measure 與 layout 都結束之後,流程進入 draw 階段。顧名思義,視圖的實際繪製就是在這裡發生的。

動手實踐:一個帶自定義文字的中間對齊 TextView

第一步:聲明自定義屬性

在 res/values/ 下新建 attrs.xml,用 declare-styleable 把屬性歸到一個樣式集合裡:

<!--?xml version="1.0" encoding="utf-8"?-->
<resources>
    <declare-styleable name="CustomTextView">
        <attr name="titleText" format="string" />
        <attr name="titleTextColor" format="color" />
        <attr name="titleTextSize" format="dimension" />
    </declare-styleable>
</resources>

接著在布局裡使用它。關鍵一步是引入自己的命名空間,格式為 xmlns:前綴="https://schemas.android.com/apk/res/包名":

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res/com.hx.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.hx.test.customtextview.CustomTextView
        android:layout_width="200dp"
        android:layout_height="100dp"
        custom:titleText="CustomTextView"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="20sp" />
</RelativeLayout>

第二步:在構造方法中讀取屬性

View 有三個構造方法,布局文件 inflate 時走的是兩參數的那個。所以標準做法是讓另外兩個構造方法都把請求轉發給三參數版本,所有初始化邏輯集中在三參數構造裡:

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

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

/**
 * 集中讀取自定義樣式屬性
 */
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.getTheme().obtainStyledAttributes(
            attrs, R.styleable.CustomTextView, defStyle, 0);
    int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case R.styleable.CustomTextView_titleText:
                mTitleText = a.getString(attr);
                break;
            case R.styleable.CustomTextView_titleTextColor:
                mTitleTextColor = a.getColor(attr, Color.BLACK);
                break;
            case R.styleable.CustomTextView_titleTextSize:
                // 默認 16sp,TypedValue 可以幫我們把 sp 換算成 px
                mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                break;
        }
    }
    a.recycle();

    // 提前算好文字邊界,後面定位要用
    mPaint = new Paint();
    mPaint.setTextSize(mTitleTextSize);
    mPaint.setColor(mTitleTextColor);
    mBound = new Rect();
    mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
}

第三步:onDraw 中把內容畫出來

先用系統默認的 onMeasure,繪製邏輯放在 onDraw 裡:先鋪一層綠色底色,再把文字居中畫上去。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    mPaint.setColor(Color.GREEN);
    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

    mPaint.setColor(mTitleTextColor);
    canvas.drawText(mTitleText,
            getWidth() / 2 - mBound.width() / 2,
            getHeight() / 2 + mBound.height() / 2,
            mPaint);
}

wrap_content 為什麼不聽話

功能基本通了,但只要把布局的寬高改成 wrap_content,效果立刻走樣:

原因在於:wrap_content 對應的 specMode 是 AT_MOST,specSize 則是父容器可用空間,於是我們直接採用了系統測量結果,視圖自然鋪滿了整個可用區域。這正是需要接管 onMeasure 的時刻——自己判斷 specMode,AT_MOST 時按「內容尺寸 + padding」計算:

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

    int width;
    int height;

    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else {
        mPaint.setTextSize(mTitleTextSize);
        mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
        int desired = (int) (getPaddingLeft() + mBound.width() + getPaddingRight());
        width = desired;
    }

    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else {
        mPaint.setTextSize(mTitleTextSize);
        mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
        int desired = (int) (getPaddingTop() + mBound.height() + getPaddingBottom());
        height = desired;
    }

    setMeasuredDimension(width, height);
}

布局同步改成 wrap_content 並加上 padding:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res/com.hx.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.hx.test.customtextview.CustomTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        custom:titleText="CustomTextView"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="20sp" />
</RelativeLayout>

現在無論寬高怎麼設置都符合預期,一個可用的自定義 View 就誕生了。

加上互動:點擊切換文字

在構造方法裡掛個點擊監聽,每次點擊換一段隨機文案:

this.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        mTitleText = randomText();
        postInvalidate();
        // invalidate();
    }
});

private String[] Str = {"Text0", "Text1", "Text2", "Text3", "Text4"};

private String randomText() {
    Random random = new Random();
    return Str[random.nextInt(5)];
}

點擊生效了,文字每次都會變化。postInvalidate() 的作用就是讓 View 重新走一遍 onDraw,這裡換成 invalidate() 也有效果,兩者的差異在於:invalidate() 必須在 UI 線程中調用,工作線程要刷新界面得通過 Handler 通知 UI 線程;而 postInvalidate() 可以直接在工作線程中調用。

還差一步:文字變短了,寬度卻沒變

仔細看會發現,文字變短之後 View 的寬度並沒有收窄,這顯然不符合 wrap_content 的語義。原因是 postInvalidate() 只觸發重繪,而寬高是在 onMeasure 裡定的,必須連測量一起重跑:

this.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        mTitleText = randomText();
        requestLayout();
    }
});

這下效果就完整了。

requestLayout 與 invalidate 的分工

requestLayout():當 View 認為自己已經不適合當前區域時,調用此方法向上請求父容器重新執行 onMeasure 與 onLayout,重新確定自己的位置與尺寸。特別是 LayoutParams 發生變化但尚未生效時(例如改了 getLayoutParams().width),就應該調用它。

invalidate():只讓 View 重畫一次,也就是重跑 onDraw,不涉及測量與布局。

一句話概括:改尺寸用 requestLayout,只改內容用 invalidate。

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