編輯:關於 Android 程式設計
寫自定義控件的時候,或多或少都會碰到 obtainStyledAttributes(AttributeSet, int[], int, int) 或者 obtainAttributes(AttributeSet, int[])。這幾個方法名字長得像繞口令,參數含義也容易搞混,稍微寫錯一個,屬性就不生效,而且往往還不報錯。這篇把它們一次講清楚。
它們的核心作用是一致的:根據傳入的參數返回一個對應的 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>
官方文檔的說法是: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。不信可以自己試一下,結論一致。
官方描述: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 資源。
官方描述: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 或者判空處理,避免用戶忘記寫屬性時直接崩潰。
這是最強 also 最容易暈的一個。官方描述翻譯過來是:返回與 attrs 對應的數組;如果 AttributeSet 中為 attrs 指定了 style 屬性,則該樣式也會被應用。
最終的屬性值由四個因素共同決定,優先級從高到低依次是:
理解這個優先級鏈,四種測試結果就都能解釋了。
參數含義:
准備資源。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 且包含值,後兩個參數的作用體現不出來。
TypedArray _TypedArray = mContext.getTheme().obtainStyledAttributes(
null,
R.styleable.MyFirstCustomerView,
R.attr.myCustomerStyle,
R.style.MyFirstCustomerViewStyle_3);
結果變成了「第四種(2)」,應用的正是第三個參數 defStyleAttr 所指向的樣式。
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)採用的標準做法。
Android 客戶端 POST 請求服務端:HttpPost 與 JSON 解析
Android 客戶端與伺服器溝通時,POST 是常見方式。相較於 GET 把參數放在 URL,POST 會把資料放在請求本文中,適合傳送較長或較敏感的內容。實作時,通常
Content Provider 跨應用共享資料的原理剖析
本文參考羅升陽先生的〈Android 應用程序組件 Content Provider 在應用程序之間共享數據的原理分析〉一文與《Android 系統源代碼情景分析》,並以
Android Shape 詳解:用 XML 輕鬆定義矩形、圓形、漸變與描邊背景
說白了,shape 就是用來在 XML 文件裡定義各種形狀的一種手段,系統解析之後,它就能像普通 Drawable 一樣被直接使用。掌握它,能讓你在不寫一行繪製代碼的前提
GreenDao 深度解析:從 ORM 選型、專案配置到四大核心類源碼
為什麼需要 ORM 做 Android 開發,遲早會碰到 SQLite。問題是它要求你親手寫 SQL、自己解析 Cursor、手動把欄位對應到物件——樣板程式碼多,出錯機