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

自定義控件第三講:obtainStyledAttributes 四大方法逐一拆解

編輯:關於 Android 程式設計

寫自定義控件的時候,或多或少都會碰到 obtainStyledAttributes(AttributeSet, int[], int, int) 或者 obtainAttributes(AttributeSet, int[])。這幾個方法名字長得像繞口令,參數含義也容易搞混,稍微寫錯一個,屬性就不生效,而且往往還不報錯。這篇把它們一次講清楚。

它們的核心作用是一致的:根據傳入的參數返回一個對應的 TypedArray,讓你能按索引讀取自定義屬性值。

四個獲取 TypedArray 的方法

// 以下三個是 Resources.Theme 的方法
1. public TypedArray obtainStyledAttributes(int[] attrs)
2. public TypedArray obtainStyledAttributes(int resid, int[] attrs)
4. public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs,
                                           int defStyleAttr, int defStyleRes)

// 這一個是 Resources 的方法
3. public TypedArray obtainAttributes(AttributeSet set, int[] attrs)

先記住這個歸屬差異:1、2、4 掛在 Theme 上,只有 3 掛在 Resources 上。這個細節決定了它們的取值來源完全不同。

準備工作

在 values 下新建 attrs.xml:

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

在 layout 下新建 activity_main.xml:

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:first_customer="https://schemas.android.com/apk/res/com.smart.customer_view_03_19"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}">

    <com.smart.customer_view_03_19.customerview.MyFirstCustomerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="@dimen/small_padding"
        first_customer:text="第一種"
        first_customer:textColor="@color/green"
        first_customer:textSize="@dimen/x_large_font" />

</RelativeLayout>

方法一:obtainStyledAttributes(int[] attrs)

官方文檔的說法是:Return a TypedArray holding the values defined by Theme which are listed in attrs。翻譯過來就是——返回一個數組,其中各屬性的值由主題(Theme)指定。

關鍵詞是 Theme。也就是說這個方法只從當前應用的主題中取值,布局文件裡寫的屬性值完全不參與。

先在清單文件中指定主題:

<intent-filter>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

在 styles 文件中定義主題:

<!-- MyAppTheme_1 -->
<style name="MyAppTheme_1" parent="@android:style/Theme.Light.NoTitleBar">
    <item name="textColor">@color/red</item>
    <item name="text">第一種</item>
    <item name="textSize">@dimen/x_large_font</item>
</style>

在構造函數中獲取:

TypedArray _TypedArray = mContext.getTheme()
        .obtainStyledAttributes(R.styleable.MyFirstCustomerView);

運行後可能會看到一堆奇怪的字符。打斷點追下去,發現從 getString() 取值的那一刻數據就已經不對了。遇到這種情況,可以在構造函數裡加一道兜底:

if (!TextUtils.isEmpty(mText)) {
    mText = "第一種";
}

順帶說一個容易誤解的地方:即使你在布局文件裡給 first_customer:text 賦了值,這個方法也不會讀到它,因為取值來源被限定在 Theme。不信可以自己試一下,結論一致。

方法二:obtainStyledAttributes(int resid, int[] attrs)

官方描述:Return a TypedArray holding the values defined by the style resource resid which are listed in attrs。

與方法一的差別只有一處:值的來源從「當前主題」換成了「指定的樣式資源 resid」。這其實是更實用的一個重載,因為你不必為了取幾個默認值而專門定製整個應用的主題。

定義樣式:

<!-- 第二種:此時不需要在布局文件中聲明自定義屬性 -->
<!-- MyFirstCustomerViewStyle_1 -->
<style name="MyFirstCustomerViewStyle_1">
    <item name="textColor">@color/green</item>
    <item name="text">第二種</item>
    <item name="textSize">@dimen/x_large_font</item>
</style>

構造函數中傳入 resid:

TypedArray _TypedArray = mContext.getTheme()
        .obtainStyledAttributes(R.style.MyFirstCustomerViewStyle_1,
                                R.styleable.MyFirstCustomerView);

同樣地,布局文件中的賦值不會生效,因為值全部來自 style 資源。

方法三:obtainAttributes(AttributeSet set, int[] attrs)

官方描述:Retrieve a set of basic attribute values from an AttributeSet, not performing styling of them using a theme and/or style resources。

重點在後半句:不做任何樣式處理。它單純地從 AttributeSet 中把屬性值撈出來,不查主題、不查 style。這也是自定義控件中最常用的一個方法。

布局文件:

<!-- first_customer:text="第三種" -->
<com.smart.customer_view_03_19.customerview.MyFirstCustomerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:padding="@dimen/small_padding"
    first_customer:text="第三種"
    first_customer:textColor="@color/blue"
    first_customer:textSize="@dimen/x_large_font" />

構造函數:

TypedArray _TypedArray = mContext.getResources()
        .obtainAttributes(attrs, R.styleable.MyFirstCustomerView);

這裡有個必須牢記的差異:AttributeSet 中的數據是從布局文件裡解析出來的,所以如果你不在布局文件中為這些屬性賦值,就會報錯。這與前兩個方法正好相反。實踐中通常會配合 try-catch 或者判空處理,避免用戶忘記寫屬性時直接崩潰。

方法四:obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes)

這是最強 also 最容易暈的一個。官方描述翻譯過來是:返回與 attrs 對應的數組;如果 AttributeSet 中為 attrs 指定了 style 屬性,則該樣式也會被應用。

最終的屬性值由四個因素共同決定,優先級從高到低依次是:

  1. AttributeSet 中直接定義的屬性值(Any attribute values in the given AttributeSet)
  2. AttributeSet 中名為 style 的屬性所指向的樣式資源
  3. 由 defStyleAttr 與 defStyleRes 指定的默認樣式資源
  4. 主題中的基礎值(The base values in this theme)

理解這個優先級鏈,四種測試結果就都能解釋了。

參數含義:

  • AttributeSet set:XML 中定義的屬性值,可能為 null。
  • int[] attrs:目標屬性列表。
  • int defStyleAttr:指向當前主題中某個樣式資源引用,該樣式為 TypedArray 提供默認值。傳 0 表示不做默認值設置。
  • int defStyleRes:默認的樣式資源。只有在 defStyleAttr 為 0,或在對應主題下找不到資源時才會生效。傳 0 表示不做默認設置。

准備資源。attrs.xml:

<resources>
    <declare-styleable name="MyFirstCustomerView">
        <!-- 第四種 -->
    </declare-styleable>
</resources>

styles.xml:

<resources>

    <!-- 第四種(2):通過主題間接引用 -->
    <style name="MyAppTheme_2" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="myCustomerStyle">@style/MyFirstCustomerViewStyle_2</item>
    </style>

    <style name="MyFirstCustomerViewStyle_2" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="textColor">@color/orange</item>
        <item name="text">第四種(2)</item>
        <item name="textSize">@dimen/x_large_font</item>
    </style>

    <!-- 第四種(3):作為 defStyleRes 的兜底 -->
    <style name="MyFirstCustomerViewStyle_3">
        <item name="textColor">@color/purple</item>
        <item name="text">第四種(3)</item>
        <item name="textSize">@dimen/x_large_font</item>
    </style>

</resources>

布局文件:

<com.smart.customer_view_03_19.customerview.MyFirstCustomerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:padding="@dimen/small_padding"
    first_customer:text="第四種(1)"
    first_customer:textColor="@color/blue"
    first_customer:textSize="@dimen/x_large_font" />

構造函數:

TypedArray _TypedArray = mContext.getTheme().obtainStyledAttributes(
        attrs,
        R.styleable.MyFirstCustomerView,
        R.attr.myCustomerStyle,
        R.style.MyFirstCustomerViewStyle_3);

這是默認情況。此時 AttributeSet 不為 null 且包含值,後兩個參數的作用體現不出來。

把 AttributeSet 傳成 null

TypedArray _TypedArray = mContext.getTheme().obtainStyledAttributes(
        null,
        R.styleable.MyFirstCustomerView,
        R.attr.myCustomerStyle,
        R.style.MyFirstCustomerViewStyle_3);

結果變成了「第四種(2)」,應用的正是第三個參數 defStyleAttr 所指向的樣式。

再把 defStyleAttr 傳成 0

TypedArray _TypedArray = mContext.getTheme().obtainStyledAttributes(
        null,
        R.styleable.MyFirstCustomerView,
        0,
        R.style.MyFirstCustomerViewStyle_3);

這次生效的是第四個參數 defStyleRes,顯示「第四種(3)」。把前面那條優先級鏈擺出來對照:

AttributeSet > style 屬性 > defStyleAttr > defStyleRes > 主題默認值

三種結果就都能解釋了。

總結與選型建議

四個方法一次列清:

1. obtainStyledAttributes(int[] attrs)                              // 取值來源:當前主題
2. obtainStyledAttributes(int resid, int[] attrs)                    // 取值來源:指定 style
3. obtainAttributes(AttributeSet set, int[] attrs)                   // 取值來源:布局文件,不做樣式
4. obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes)     // 多級 fallback

其中第三個和第四個最常用,也覆蓋了絕大多數自定義控件的場景。

實踐中有一條通用建議:無論用哪個方法,取完屬性後記得調用 typedArray.recycle()。TypedArray 內部持有資源引用,不釋放會造成內存壓力,這是在列表視圖中反覆創建控件時最容易暴露的問題。

另外,如果你希望自定義控件既支持布局中直接寫屬性、又支持通過 style 定製默認外觀、還能被子主題覆蓋,那麼唯一正確的選擇就是方法四,並把 defStyleAttr 指向一個在主題中聲明的 attr 引用。這也是 Google 官方自定義控件(如 AppCompatButton、MaterialCardView)採用的標準做法。

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