Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 高手進階教程(四):自訂屬性 attrs.xml 與 TypedArray 實戰

編輯:Android 開發實例

上一篇我們把自訂 View 的基本寫法走過一遍,這一篇要往前推進一步——讓我們自己寫的元件也能像官方控制項那樣,在 XML 裡配置屬性。

如果你還沒看過前一課,建議先補上《Android 高手進階教程(三)》,兩篇連著讀會順很多。

為什麼要自己定義屬性

寫布局時我們早就習慣了 android:text=""、android:textColor="" 這類寫法。那麼,能不能替自己的元件也開一組屬性,寫成 test:attrs="" 的樣子?答案是可以的。而且這一步往往是自訂元件從「能跑」走向「好用」的分水嶺。

整個流程可以拆成四個環節:宣告屬性 → 在構造方法中用 TypedArray 取值 → 在布局裡掛上命名空間前綴 → 編譯執行驗證。

步驟一:在 res/values 下新增 attrs.xml

先在 res/values 目錄建立一個 attrs.xml,用 <declare-styleable> 標籤把屬性打包成一個「樣式集合」:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

這裡有兩個關鍵點。第一,name="MyView" 是這個樣式集合的名字,後面在 Java 程式碼裡取屬性會用到它。第二,format 用來約束屬性的值類型,常見的有 color、dimension、string、boolean、integer、reference 等等;寫對 format,才能在程式碼裡呼叫對應的 getColor()、getDimension() 這類方法。

步驟二:在 MyView.java 中讀取屬性

真正的重點在「帶有 AttributeSet 參數的那個構造方法」。當元件是透過 XML 布局被 inflate 出來的時候,系統呼叫的就是這一個建構子,屬性值也只能在這裡拿到。

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();

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

    int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
    float textSize = a.getDimension(R.styleable.MyView_textSize, 36);

    mPaint.setTextSize(textSize);
    mPaint.setColor(textColor);

    a.recycle();
}

幾個容易踩坑的細節:

  • R.styleable.MyView 對應的是 attrs.xml 裡 <declare-styleable name="MyView"> 的名字。
  • 單一屬性用「集合名 + 底線 + 屬性名」串接,也就是 R.styleable.MyView_textColor。這個常數會由 aapt 自動產生,寫錯名字編譯不會過。
  • getColor()、getDimension() 的第二個參數是預設值。一旦布局裡沒有寫這個屬性,就會退回預設值,這能有效避免空值造成的異常。本例中顏色預設不透明白色,字級預設 36。
  • 用完 TypedArray 一定要呼叫 recycle()。這是為了讓資源能被後續的屬性讀取重複利用,養成習慣比較保險。

MyView.java 完整程式碼

package com.android.tutor;

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

public class MyView extends View {

    private Paint mPaint;
    private Context mContext;
    private static final String mString = "Welcome to Mr Wei's blog";

    public MyView(Context context) {
        super(context);
        mPaint = new Paint();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();

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

        int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);

        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);

        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 設定為填滿樣式
        mPaint.setStyle(Style.FILL);

        // 畫一個矩形,前兩個數字是左上角座標,後兩個是右下角座標
        canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);

        mPaint.setColor(Color.BLUE);

        // 繪製文字
        canvas.drawText(mString, 10, 110, mPaint);
    }
}

值得留意的是:在 onDraw() 裡我們把畫筆顏色又改回藍色,所以自訂屬性 textColor 實際影響的是矩形填色,文字顏色則被程式碼覆蓋了。這是原作者的示範寫法,自己在實作時記得釐清「哪個屬性控制哪個圖形」。

步驟三:把 MyView 放進 main.xml

要在布局中使用自訂屬性,必須先在根節點宣告命名空間:

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

其中 test 是自訂的前綴,名稱可以隨意取;後面那段 URI 則固定是 https://schemas.android.com/apk/res/ 再加上你的應用套件名稱。這也是為什麼自訂屬性寫起來會是 test:textSize 這種形式。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:test="https://schemas.android.com/apk/res/com.android.tutor"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />

    <com.android.tutor.MyView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        test:textSize="20px"
        test:textColor="#fff"
        />

</LinearLayout>

步驟四:編譯執行

跑起來之後,畫面上會出現一個矩形與一行文字。此時試著改動 test:textSize 與 test:textColor 的值,重新執行,你會看到矩形的大小與顏色跟著改變——這就代表自訂屬性已經完整打通了。再把這兩個屬性整行刪掉執行一次,矩形會退回預設的白色、36 的字級,這正好驗證了預設值機制也生效。

小結

自訂屬性的核心其實只有三件事:在 attrs.xml 宣告、在帶 AttributeSet 的建構子裡用 TypedArray 取值、在布局中宣告命名空間前綴。把這三步練熟,你就能開始包裝出真正可重複使用、可交由設計人員在 XML 裡微調的自家元件庫。

有疑問歡迎留言討論。

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