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

Android 自訂 View 入門整理:從 onMeasure 到自訂屬性

編輯:關於 Android 程式設計

為什麼要自訂 View

開發時難免遇到這種狀況:系統提供的控制項怎麼調都貼不上設計稿的細節。這時候就該自己動手做一個 View 了。

自訂 View 大體分成兩類:一類是繼承 View 的自訂控制項,另一類是繼承 ViewGroup 的自訂版面配置容器。本文先聚焦在前者。

自訂 View 最少要動哪幾個方法

大部分情況下,只要覆寫 onMeasure() 與 onDraw() 兩個方法:前者負責量測自己的尺寸,後者負責把自己畫出來。此外,還必須寫一個帶 AttributeSet 參數的建構子。

建構子:兩個都要留著

public CustView(Context context) {
    super(context);
}

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

這兩個建構子對應兩種建立方式。用純程式碼建立時走第一個:

CustView custView = new CustView(this);

如果是從 XML 版面檔 inflate 出來的,系統會呼叫第二個。這個建構子不能省,因為系統正是透過它,把 XML 裡寫在這個 View 上的屬性傳進來;少了它,執行期就會直接拋例外。

Google 文件的說法很明白:這個建構子會在「從 XML inflate 一個 View」時被呼叫,並把 XML 檔中指定的屬性一併帶入;這個版本使用預設樣式 0,因此只有套用的屬性值來自 Context 的主題與傳入的 AttributeSet。

覆寫 onMeasure():自己決定尺寸

XML 裡的 layout_width 與 layout_height 除了寫死數值,還可以填 wrap_content 或 match_parent,分別代表「包住內容」與「撐滿父親給的空間」。系統預設會針對這兩種值做處理,但我們可以透過覆寫 onMeasure() 拿到決定權。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

兩個參數分別代表父容器在水平與垂直方向上施加的 constraint。說得更具體一點,它們各自打包了「尺寸大小」與「量測模式」兩部分資訊。

尺寸有三種寫法(明確數值、match_parent、wrap_content),量測模式也有三種:

  • UNSPECIFIED:父容器沒有施加任何限制,子 View 想多大就多大。
  • EXACTLY:父容器已經定好確切尺寸,子 View 必須遵守。
  • AT_MOST:這個尺寸是子 View 能用的上限。

用 MeasureSpec 就能把兩部分資訊拆出來:

int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);

對應關係是這樣的:

match_parent → EXACTLY。父親尺寸是確定的,所以子 View 也確定。

wrap_content → AT_MOST。以父親尺寸為參考上限,只要不超過就好。

明確數值(例如 100dp)→ EXACTLY。使用者已經講死了,性質等同 match_parent。

下面實作一個「寬高一律相等」的正方形 View,預設邊長 100px,若外部指定更大的值則以外部為準:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = getSize(100, widthMeasureSpec);
    int height = getSize(100, heightMeasureSpec);
    if (width > height) {
        width = height;
    } else {
        height = width;
    }
    setMeasuredDimension(width, height); // 必須存回量測結果,否則不生效
}

private int getSize(int defaultSize, int measureSpec) {
    int mySize = defaultSize;
    int size = MeasureSpec.getSize(measureSpec);
    int mode = MeasureSpec.getMode(measureSpec);
    switch (mode) {
        case MeasureSpec.UNSPECIFIED:
            // 未指定大小,採用預設值
            mySize = defaultSize;
            break;
        case MeasureSpec.EXACTLY:
            // 版面指定的值大於預設值時採用它,對應 match_parent 與明確數值
            if (size > defaultSize) {
                mySize = size;
            }
            break;
        case MeasureSpec.AT_MOST:
            // 上限值大於預設值時仍取預設值,對應 wrap_content
            if (size > defaultSize) {
                mySize = defaultSize;
            }
            break;
    }
    return mySize;
}

版面檔的寫法:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager_box"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <com.yuminfeng.myviewpager.CustView
        android:id="@+id/custView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@android:color/holo_red_dark" />
</LinearLayout>

有覆寫 onMeasure 時,View 會被強制收成正方形:

把 onMeasure 註解掉之後,就會變回系統預設的計算結果:

覆寫 onDraw():把東西畫出來

下面在 View 上畫一個空心的圓:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int r = getMeasuredWidth() / 2; // 用 getMeasuredWidth 拿到 onMeasure 中算出的寬度
    canvas.drawCircle(r, r, r - 20, mPaint);
    // 前兩個參數是圓心的 x、y,座標相對於「這個 View 自己」,與其它 View 的位置無關
}

畫筆 Paint 在建構子裡初始化即可:

private void initPaint() {
    mPaint = new Paint();
    mPaint.setAntiAlias(true);              // 抗鋸齒
    mPaint.setStyle(Paint.Style.STROKE);    // 描邊而非填色
    mPaint.setStrokeWidth(3);               // 筆刷粗細
    mPaint.setColor(Color.BLUE);            // 顏色
}

效果如下:

加上自訂屬性

給自訂 View 開一些自訂屬性,使用者在 XML 裡就能直接調整行為,擴充性會好很多。

先在 res/values 下建立 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- name 是屬性集合的名稱,可自取,但建議與 View 同名 -->
    <declare-styleable name="CustView">
        <!-- 在這裡宣告各項屬性,注意 format 的選用 -->
    </declare-styleable>
</resources>

每個屬性都要指定 format,常見的有 color、dimension、string、boolean、integer、reference 等,選錯會導致值無法正確解析。

接著在版面檔中使用這些屬性:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custview="https://schemas.android.com/apk/res/com.yuminfeng.myviewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <com.yuminfeng.myviewpager.CustView
        android:id="@+id/custView"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        custview:paintColor="@android:color/holo_orange_dark"
        custview:paintSize="10dp" />
</LinearLayout>

重點:用自訂屬性前一定要宣告命名空間。前綴名稱可以自取(這裡是 custview),但命名空間的值有固定格式,也就是 "https://schemas.android.com/apk/res/" 加上你的套件包名。宣告好之後才能寫 custview:paintColor、custview:paintSize 這類屬性。

最後在程式碼中把值讀出來:

private void initAttrs(Context context, AttributeSet attrs) {
    // 取出 attrs 中的 CustView 屬性;CustView 就是 attrs.xml 裡 declare-styleable 的名稱
    TypedArray type = context.obtainStyledAttributes(attrs, R.styleable.CustView);

    // 命名規則為 R.styleable.屬性集合名稱_屬性名稱,取不到時使用預設值
    paintColor = type.getColor(R.styleable.CustView_paintColor, Color.BLACK);
    paintSize = (int) type.getDimension(R.styleable.CustView_paintSize, 3);

    type.recycle(); // 記得回收
}

完整程式碼

package com.yuminfeng.myviewpager;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class CustView extends View {

    private Paint mPaint;
    private int paintColor;
    private int paintSize;

    public CustView(Context context) {
        super(context);
        initPaint();
    }

    public CustView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        initPaint();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray type = context.obtainStyledAttributes(attrs, R.styleable.CustView);
        paintColor = type.getColor(R.styleable.CustView_paintColor, Color.BLACK);
        paintSize = (int) type.getDimension(R.styleable.CustView_paintSize, 3);
        type.recycle();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(paintSize);
        mPaint.setColor(paintColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getSize(100, widthMeasureSpec);
        int height = getSize(100, heightMeasureSpec);
        if (width > height) {
            width = height;
        } else {
            height = width;
        }
        setMeasuredDimension(width, height);
    }

    private int getSize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;
        int size = MeasureSpec.getSize(measureSpec);
        int mode = MeasureSpec.getMode(measureSpec);
        switch (mode) {
            case MeasureSpec.UNSPECIFIED:
                mySize = defaultSize;
                break;
            case MeasureSpec.EXACTLY:
                if (size > defaultSize) {
                    mySize = size;
                }
                break;
            case MeasureSpec.AT_MOST:
                if (size > defaultSize) {
                    mySize = defaultSize;
                }
                break;
        }
        return mySize;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;
        canvas.drawCircle(r, r, r - 20, mPaint);
    }
}

搭配自訂屬性之後的效果:

自訂 View 的部分就到這裡,下一篇接著談自訂 ViewGroup。

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