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

Android 自訂控件系列(二):如何定義與讀取自訂屬性

編輯:關於 Android 程式設計

上一篇談了如何測量控件尺寸,這篇接著講另一個必要知識:自訂屬性。對一個真正有實用價值、能被別人 reuse 的控件來說,自訂屬性是絕對不可少的——否則使用者只能透過一堆 setter 來配置,XML 預覽也完全失效。

一、如何定義屬性

在 res/values/attrs.xml(若不存在可自行建立)中,用 <declare-styleable> 標籤把同一組屬性綁在一起。以下以一個顯示圓形頭像的控件 AvatarImageView 為例:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="avatarimageview">
        <attr name="src" format="reference" />
        <attr name="border" format="dimension" />
        <attr name="borderColor" format="reference|color" />
        <attr name="borderAlpha" format="integer" />
    </declare-styleable>
</resources>

幾個關鍵點:

  • name="avatarimageview":這組屬性的名稱,一般直接寫成控件名稱,用來標識「這些屬性屬於某個控件」。實際上這也是 R.styleable 中會產生的類別名稱來源。
  • format 指定屬性值的型別,常見的有:
    • reference:引用型別,如引用圖片、顏色、文字資源。
    • dimension:dp/px 等尺寸值。
    • integer:整數。
    • color:顏色編碼。
    • boolean、string、float、enum、flag 等。
  • 多型別支援:若一個屬性兩種寫法都要吃(例如 borderColor 既可直接寫 #FF0000,也可寫 @color/red),中間用豎線分隔:format="reference|color"。若顏色只在 colors.xml 中定義,則單純用 reference 即可。

二、如何在程式中取得屬性值

定義屬性終究是為了拿它來畫。以本例來說,沒有 src 就不知道要畫哪張圖,沒有 border 就不知道邊框要多粗。所以必須在控件實例化的過程中把值讀出來。

View 有兩個需要重寫的建構子:

  • View(Context context):用於純 Java 程式碼建立控件時。這種情況下屬性完全可以直接用 setXxx() 注入,attrs 派不上用場。
  • View(Context context, AttributeSet attrs):從 XML inflate 時呼叫。這才是我們要的重點,屬性值就藏在 AttributeSet 裡。

讀取的做法是用 obtainStyledAttributes() 把整組屬性轉成 TypedArray,再逐一取出:

public AvatarImageView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.avatarimageview);

    src = a.getResourceId(R.styleable.avatarimageview_src, 0);
    if (src != 0) {
        bitmap = BitmapFactory.decodeResource(this.getResources(), src);
    }

    border = (int) a.getDimension(R.styleable.avatarimageview_border,
            dip2px(this.getContext(), 6));

    borderColor = (int) a.getColor(R.styleable.avatarimageview_borderColor, 0);
    if (borderColor == 0) {
        borderColor = a.getResourceId(R.styleable.avatarimageview_borderColor, 0);
    }
    if (borderColor == 0) {
        borderColor = 0x9F7A97EA;   // 給一個預設值,避免畫出來是黑的
    }

    borderAlpha = a.getInt(R.styleable.avatarimageview_borderAlpha, -1);

    a.recycle();   // 很重要,別忘了歸還
}

這裡有兩個實務細節:一是每個 getter 都帶預設值,使用者沒寫屬性時才不會 crash;二是 borderColor 那段做了兩段式取值,因為 format 同時允許 color 與 reference,先試 getColor,失敗再試 getResourceId,這樣兩種寫法都能支援。三是 recycle()——TypedArray 是從資源池借來的,用完必須歸還,否則會造成資源洩漏。

三、如何在 layout 中使用

自訂屬性要用自己的命名空間引用。命名空間的名稱(這裡是 my)可以自取,後面接的則是控件所在的 package 名稱:

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:my="https://schemas.android.com/apk/res/com.kanyuan.avatarimageview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <com.kanyuan.avatarimageview.AvatarImageView
        android:id="@+id/avatarImageView"
        my:src="@drawable/head"
        my:border="2dp"
        android:layout_width="200dp"
        android:layout_height="200dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="改變頭像"
        android:onClick="changeAvatar" />

</LinearLayout>

寫法重點:先宣告 xmlns:命名空間名稱="https://schemas.android.com/apk/res/應用的包名",之後就能用 my:src、my:border 這種方式引用。

與上一篇的接軌

把這篇和上一篇串起來就完整了:透過自訂屬性取得 padding、border 等參數,再依這些參數在 onMeasure 中算出控件實際需要多大的空間,最後在 onDraw 中把它畫出來。這三件事就是自訂控件的全部骨架。

最後補一個實務建議:如果你只是想給現有控件加一兩個行為(例如「是否可以點擊」),優先考慮自訂 attribute;但若是大量的樣式組合,改用 style 或 theme attribute 會更彈性,也不必為每個變體寫一個控件類別。

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