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

Android 自定義視圖與自定義屬性完整指南

編輯:關於 Android 程式設計

本文整理自 Android UI Fundamentals 的相關內容,示範如何從零打造一個自定義 View,並透過 XML 屬性為它注入可配置的能力。

一、建立自定義視圖

要建立自定義 UI 元件,第一步就是繼承一個既有的 View 類別。這裡我們做一個簡單的 CrossView,畫面呈現是一條十字線。

首先建立繼承自 View 的 CrossView,並準備好接收 XML 參數的建構子:

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

第二個參數 AttributeSet 就是 XML 屬性的載體,後面會用到。接著要覆寫兩個關鍵方法:onMeasure 與 onDraw。

onMeasure:決定自己的尺寸

系統會呼叫 onMeasure 來決定這個檢視及其子檢視的大小。它的兩個參數型別都是 int,但並不是普通數字,而是兩個 MeasureSpec——模式與尺寸值的打包結果。模式有三種:

UNSPECIFIED:父檢視沒有對這個檢視做任何限制,可以是任意尺寸。
AT_MOST:這個檢視的大小必須小於等於 MeasureSpec 中的尺寸。
EXACTLY:父檢視要求這個檢視必須正好是 MeasureSpec 指定的尺寸。

覆寫 onMeasure 時必須正確處理每一種情況,並且在方法結尾呼叫 setMeasuredDimension(),否則會直接拋出異常。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(calculateMeasure(widthMeasureSpec),
                         calculateMeasure(heightMeasureSpec));
}

先定義一個預設尺寸 100:

private static final int DEFAULT_SIZE = 100;

再乘上螢幕像素密度,換算成實際需要的像素值:

int result = (int) (DEFAULT_SIZE * getResources().getDisplayMetrics().density);

接著取出模式與尺寸:

int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);

然後依模式決定 result 最終該是多少:

當模式是 UNSPECIFIED,父容器沒有要求,就用預設值。
當模式是 AT_MOST,取「指定值」與「預設值」中比較小的那個,這樣無論如何都不會超限。
當模式是 EXACTLY,直接採用父容器給的尺寸。

private static final int DEFAULT_SIZE = 100;

private int calculateMeasure(int measureSpec) {
    int result = (int) (DEFAULT_SIZE * getResources().getDisplayMetrics().density);
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    if (specMode == MeasureSpec.EXACTLY) {
        result = specSize;
    } else if (specMode == MeasureSpec.AT_MOST) {
        result = Math.min(specSize, result);
    }
    return result;
}

onDraw:決定怎麼畫

當檢視需要繪製內容時,系統會呼叫 onDraw。覆寫它之前,先準備一個 Paint 物件,用來處理顏色、線寬、文字大小這類繪製參數。我們在建構子裡建立它:

private Paint mPaint;

public CrossView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setColor(0xffff0000);
}

這裡設定了抗鋸齒與紅色。接著覆寫 onDraw:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    // 繪製程式碼放在這裡
    canvas.restore();
}

一個小技巧:先對畫布做縮放,之後就能用 0 到 1 之間的浮點數當座標,不必自己換算螢幕解析度。

private static final float[] mPoints = {
        0.5f, 0f, 0.5f, 1f,   // 垂直線
        0f, 0.5f, 1f, 0.5f    // 水平線
};

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.scale(getWidth(), getHeight());
    canvas.drawLines(mPoints, mPaint);
    canvas.restore();
}

在 XML 裡掛上這個自定義控件:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.shaw.uitest.CrossView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <com.shaw.uitest.CrossView
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

執行起來就會看到文章開頭那張圖的效果。

二、加上自定義屬性

有了自定義視圖之後,自然會希望它能透過 XML 屬性來配置。流程是三步:宣告屬性、在布局中宣告命名空間、在程式碼中解析 AttributeSet。

宣告屬性

在 res/values/ 下新增一個 attrs.xml(檔名可自訂):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="cross">
        <attr name="rotation" format="float" />
    </declare-styleable>
</resources>

declare-styleable 的 name 屬性用於在程式碼中引用這組屬性;每個屬性用一個 attr 元素宣告,有 name 與 format 兩個屬性,format 代表資料型別。如果沿用系統已有的屬性(例如 android:color),就不必重新定義 format;但若試圖給既有屬性宣告一個不同的 format,專案會直接 build 失敗。

屬性也可以定義自訂列舉值或旗標:

<attr name="orientation">
    <enum name="value1" value="1" />
    <enum name="value2" value="2" />
</attr>

<attr name="flags">
    <flag name="flag1" value="0x01" />
    <flag name="flag2" value="0x02" />
</attr>

enum 與 flag 都必須是整數,差別在於 flag 可以用 | 串接多個值,例如 android:gravity 就是典型的 flag。

在 XML 中使用

要用自定義屬性,必須先為檢視宣告 namespace。我們常見的

xmlns:android="https://schemas.android.com/apk/res/android"

聲明了所有以 android: 開頭的屬性都能在 android 套件中找到。自定義屬性則要用 res-auto:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:crossview="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.shaw.uitest.CrossView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:color="#ff0000ff"
        crossview:rotation="30" />

    <com.shaw.uitest.CrossView
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:color="#ff00ff00"
        crossview:rotation="50" />

</LinearLayout>

這樣就聲明了所有以 crossview 開頭的屬性都到 res 裡去找。前綴名稱可以自訂,但 URI 固定寫 res-auto 是 Gradle 建置系統要求的寫法。

在程式碼中解析

建構子傳入的 AttributeSet 就是屬性的來源,透過 obtainStyledAttributes() 取出 TypedArray 後即可讀值:

private float mRotation;

public CrossView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);

    TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.cross);
    int color = arr.getColor(R.styleable.cross_android_color, Color.BLACK);
    float rotation = arr.getFloat(R.styleable.cross_rotation, 0f);
    arr.recycle();          // 記得回收

    setColor(color);
    setRotation(rotation);
}

public void setColor(int color) {
    mPaint.setColor(color);
}

public void setRotation(float degree) {
    mRotation = degree;
}

同時更新 onDraw,讓旋轉生效:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.scale(getWidth(), getHeight());
    canvas.rotate(mRotation, 0.5f, 0.5f);   // 以畫布中心為旋轉軸
    canvas.drawLines(mPoints, mPaint);
    canvas.restore();
}

注意旋轉中心刻意設在畫布中心而不是左上角。執行後的效果如下:

三、兩個容易忽略的實務要點

TypedArray 一定要 recycle。它持有的是共用資源池中的物件,不歸還會造成效能與記憶體上的浪費。

自定義屬性變動後要 requestLayout / invalidate。如果屬性會影響尺寸(例如邊距、文字大小),在 setter 中呼叫 requestLayout();若只影響外觀,呼叫 invalidate() 觸發重繪即可。少了這一步,動態改屬性時畫面不會更新。

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