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

深入 Android 自定義屬性:AttributeSet、TypedArray 與 declare-styleable

編輯:關於 Android 程式設計

自定義 View 時,我們幾乎都寫過這樣一套流程:繼承 View、在 attrs.xml 裡聲明 declare-styleable、在布局裡使用自定義屬性、在構造方法中用 TypedArray 取值。但很少有人追問:這四步為什麼能生效?styleable 到底做了什麼?本文把這些問題逐一拆開。

一、常見做法速覽

聲明文件:

<resources>
    <declare-styleable name="test">
        <attr name="testAttr" format="integer" />
        <attr name="text" format="string" />
    </declare-styleable>
</resources>

在構造方法中取值:

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
    String text = ta.getString(R.styleable.test_testAttr);
    int textAttr = ta.getInteger(R.styleable.test_text, -1);
    ta.recycle();
}

布局中使用時記得聲明命名空間,例如 xmlns:zhy="https://schemas.android.com/apk/res/com.example.test",然後寫上 zhy:testAttr="520"。注意 styleable 的 name 只是給生成的常量分組,並不要求與自定義 View 的類名一致。

二、AttributeSet 能取值,那 TypedArray 還有必要嗎

構造方法裡的 AttributeSet attrs 確實保存了該標籤上的全部屬性,可以這樣遍歷:

int count = attrs.getAttributeCount();
for (int i = 0; i < count; i++) {
    Log.e(TAG, attrs.getAttributeName(i) + " = " + attrs.getAttributeValue(i));
}

輸出會類似 layout_width = 100.0dip、text = helloworld。看起來一切美好,直到你把布局改成引用:

zhy:text="@string/hello_world"
android:layout_width="@dimen/dp100"

此時 AttributeSet 拿到的是 @2131361809 這樣的資源 ID 字符串,肉眼完全無法辨認。要得到最終值,得先取 ID 再自行解析:

int widthId = attrs.getAttributeResourceValue(0, -1);
Log.e(TAG, "layout_width = " + getResources().getDimension(widthId));

TypedArray 存在的意義就在這裡:它把「取 ID → 查資源 → 類型轉換」的過程一次封裝完成,getString()、getDimension()、getInteger() 直接給你可用值。這也是系統內置 View(如 TextView)的標準做法。

三、可以直接複用系統屬性嗎

可以。系統在 sdk/platforms/android-xx/data/res/values 下定義了大量通用屬性,直接引用即可:

<declare-styleable name="test">
    <attr name="android:text" />
</declare-styleable>

取值時寫 ta.getString(R.styleable.test_android_text),布局裡寫 android:text="@string/hello_world"。差別只在於:引用已有屬性時不需要再聲明 format。

四、declare-styleable 可以不寫嗎

可以。去掉 declare-styleable 後,只需自己維護一個屬性 ID 數組和下標常量:

private static final int[] mAttr = { android.R.attr.text, R.attr.testAttr };
private static final int ATTR_ANDROID_TEXT = 0;
private static final int ATTR_TESTATTR = 1;

TypedArray ta = context.obtainStyledAttributes(attrs, mAttr);

對比不難發現,declare-styleable 的作用正是由 aapt 在 R.java 中自動生成這個數組與一堆下標常量。屬性一多,手工維護下標簡直是噩夢,所以始終建議保留聲明;name 一般寫成自定義 View 的類名,只是為了可讀性。

五、小結

  • declare-styleable 本質是「屬性集合的索引」,由 aapt 生成數組與常量,大幅減少手工維護成本。
  • AttributeSet 能拿到原始值,但引用類型會變成資源 ID;TypedArray 才是解析後的結果。
  • 用完 TypedArray 記得 recycle()。
  • 語義明確時優先複用系統屬性,能提升一致性與可讀性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved