編輯:關於 Android 程式設計
Android 內建的各種 Widget 都提供了大量 XML 屬性,讓我們能在 layout 檔案中直接為它們賦值:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
自定義 View 時,我們往往也希望它擁有屬於自己的 XML 屬性。本文以一個名為 com.ispring.attr.MyView 的 View 為例,把「定義屬性 → 解析屬性 → 使用屬性」的完整鏈路走一遍,並釐清 R.attr 與 R.styleable 的分工,以及 obtainStyledAttributes 四個參數的優先級。
整體流程只有三步:
1. 在 res/values 下新增 XML 資源檔,宣告各種 attr 並指定資料型別。
2. 在自定義 View 的建構式中解析這些屬性,存進成員變數。
3. 在 layout 檔案中為自定義 View 的屬性賦值。
我們在 res/values 建立 attrs_my_views.xml(檔名不拘,只要是 values 下的 XML 即可),根節點為 <resources>,在其中透過 name 指定屬性名、format 指定型別:

由圖可見,format 支援的型別包括 enum、boolean、color、dimension、flag、float、fraction、integer、reference、string。
宣告好之後,就能在 layout 中賦值了:

使用自定義 View 時,需要宣告一個自己的命名空間以區別於 xmlns:android。命名空間名稱可任意,慣例是 xmlns:app:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.ispring.attr.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:customText="Hello World!"
app:customColor="#FF0000FF" />
</RelativeLayout>
傳統的 https://schemas.android.com/apk/lib/com.ispring.attr 寫法在 Eclipse 時代常見,Android Studio 建專案時會自動幫你產生 https://schemas.android.com/apk/res-auto,直接沿用即可,不必手寫包名。
<attr name="customAttr">
<enum name="man" value="0" />
<enum name="woman" value="1" />
</attr>
此時 customAttr 只能取 man 或 woman。
flag 表示 this 屬性是一個 bit 位標記,與 enum 相似,但可用 | 組合成多個值,每個值對應一個 bit 位。它適合用來描述「某個欄位同時具備多項特性」的場景。注意:使用 flag 時不要在 <attr> 上設定 format,而是直接在 <attr> 節點下添加多個 <flag> 子節點。
<attr name="customAttr">
<flag name="none" value="0" />
<flag name="bold" value="0x1" />
<flag name="italic" value="0x2" />
<flag name="underline" value="0x4" />
</attr>
value 一般取 0 或 2 的 N 次方(N ≥ 0 的整數)。使用時既可設單值,也可組合:
app:customAttr="italic|underline"
讓 MyView 直接繼承自 View,目標很簡單:傳入一段文字和一個顏色,它就能畫出來,相當於一個極簡版 TextView。
<resources>
<attr name="customText" format="string" />
<attr name="customColor" format="color" />
</resources>
編譯後會產生 R.java。Android Studio 專案中,檔案位於 app/build/generated/source/r/debug/com/ispring/attr/R.java,其中的內部類 public static final class attr 會出現 customText 與 customColor:

R.attr.customText 與 R.attr.customColor 分別是兩個屬性的資源 ID。運行結果:

介面上出現藍色的「Hello World!」,說明自定義屬性已生效。MyView 的實作如下:
package com.ispring.attr;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
// 存儲要顯示的文本
private String mCustomText;
// 存儲文本的顯示顏色
private int mCustomColor = 0xFF000000;
// 畫筆
private TextPaint mTextPaint;
// 字體大小
private float fontSize = getResources().getDimension(R.dimen.fontSize);
public MyView(Context context) {
super(context);
init(null, 0);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
if (attrs != null) {
// 取得 AttributeSet 中所有 XML 屬性的數量
int count = attrs.getAttributeCount();
// 遍歷所有屬性
for (int i = 0; i < count; i++) {
// 取得屬性的資源 ID
int attrResId = attrs.getAttributeNameResource(i);
switch (attrResId) {
case R.attr.customText:
mCustomText = attrs.getAttributeValue(i);
break;
case R.attr.customColor:
// 讀不到時預設為黑色
mCustomColor = attrs.getAttributeIntValue(i, 0xFF000000);
break;
}
}
}
mTextPaint = new TextPaint();
mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(fontSize);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mCustomText != null && !mCustomText.equals("")) {
mTextPaint.setColor(mCustomColor);
canvas.drawText(mCustomText, 0, fontSize, mTextPaint);
}
}
}
關鍵在 init 方法。傳入的 AttributeSet 可以理解為一個屬性索引陣列,透過索引能取到屬性名與屬性值。幾個常用 API:
· getAttributeCount():取得屬性數量。
· getAttributeName(int index):取得屬性名稱字串。
· getAttributeNameResource(int index):取得屬性在 R.attr 中的資源 ID。
· getAttributeValue / getAttributeIntValue / getAttributeFloatValue 等:取得對應型別的屬性值。
程式先以 attrs.getAttributeNameResource(i) 拿到資源 ID 並 switch 判斷:命中 R.attr.customText 就用 getAttributeValue(i) 取值;命中 R.attr.customColor 時,由於 Android 用一個 4 位元組 int 表示顏色,改用 getAttributeIntValue(i, 0xFF000000) 取值並提供預設色。最後在 onDraw 中設定畫筆顏色並 canvas.drawText 繪製。
上面兩個屬性直接定義在 <resources> 下,這有一個明顯限制:無法透過 style 或 theme 為它們賦值。要支援這條路徑,必須改用 <declare-styleable>:
<resources>
<declare-styleable name="MyView">
<attr name="customText" format="string" />
<attr name="customColor" format="color" />
</declare-styleable>
</resources>
name 一般取自定義 View 的類名,此處為 MyView。
兩種寫法在 R.attr 中生成的結果完全一樣,差別在於:<declare-styleable name="MyView"> 還會在 R.styleable 內部類中產生額外的常量:

R.styleable.MyView 是一個 int 陣列,值為 0x7f010038 與 0x7f010039,分別對應 R.attr.customText 與 R.attr.customColor。也就是說:
R.styleable.MyView == [R.attr.customText, R.attr.customColor]
此外還能看到 R.styleable.MyView_customColor 與 R.styleable.MyView_customText——由 declare-styleable 的 name 加上屬性 name、以底線串接而成:

這兩個常量正是後面讀取 TypedArray 時用來定位索引的依據。
在 <declare-styleable> 中定義的屬性,需透過 theme 的 obtainStyledAttributes 讀取。它有三個重載:
public TypedArray obtainStyledAttributes(int[] attrs)
public TypedArray obtainStyledAttributes(int resid, int[] attrs)
public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
先來看最完整的第三個版本:
private void init(AttributeSet attributeSet, int defStyle) {
if (attributeSet != null) {
// 取得目前 Activity 的 theme
Resources.Theme theme = getContext().getTheme();
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, 0, 0);
int count = typedArray.getIndexCount();
for (int i = 0; i < count; i++) {
int styledAttr = typedArray.getIndex(i);
switch (styledAttr) {
case R.styleable.MyView_customText:
mCustomText = typedArray.getString(styledAttr);
break;
case R.styleable.MyView_customColor:
mCustomColor = typedArray.getColor(styledAttr, 0xFF000000);
break;
}
}
// 用完記得回收
typedArray.recycle();
}
...
}
在 res/values/styles.xml 中定義一個 style:
<style name="RedStyle">
<item name="customText">customText in RedStyle</item>
<item name="customColor">#FFFF0000</item> <!-- 紅色 -->
</style>
layout 中同時使用直接賦值與 style:
<com.ispring.attr.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/RedStyle"
app:customText="customText in AttributeSet" />
運行結果:

我們只設了 app:customText,沒設 app:customColor,但文字最終是紅色的——紅色來自 RedStyle。這說明了取值順序:
· layout 中直接設定的屬性(AttributeSet)優先級最高,命中即採用。
· 若 layout 沒設,但設了 style,則由 style 對應的資源補上。
· 也就是說,style 是 layout 直接賦值的「補漏」機制。
第三個參數 defStyleAttr 指向一個 style 屬性的 ID。當 AttributeSet 與 style 屬性都找不到值時,Android 會去當前 theme 中查詢該屬性的值;若該值又是一個 style 資源,就再進去那個 style 裡找屬性值。
先擴充 styles.xml:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="myViewStyle">@style/GreenStyle</item>
</style>
<style name="GreenStyle">
<item name="customText">customText in GreenStyle</item>
<item name="customColor">#FF00FF00</item>
</style>
<style name="HelloWorldStyle">
<item name="customText">Hello World!</item>
</style>
<style name="RedStyle">
<item name="customText">customText in RedStyle</item>
<item name="customColor">#FFFF0000</item>
</style>
</resources>
其中 myViewStyle 宣告為 reference 型別,指向一個 style 資源:
<resources>
<declare-styleable name="MyView">
<attr name="myViewStyle" format="reference" />
</declare-styleable>
</resources>
接著把 obtainStyledAttributes 的第三個參數換成 R.attr.myViewStyle:
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, R.attr.myViewStyle, 0);
layout 只設 style:
<com.ispring.attr.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/HelloWorldStyle" />
運行結果:

結果是綠色的「Hello World!」,推理過程如下:
· layout 沒有直接設屬性,AttributeSet 這層直接跳過。
· style 指定為 HelloWorldStyle,其中 customText 為「Hello World!」,所以文字內容由它決定。
· HelloWorldStyle 沒定義 customColor,於是查找 theme(AppTheme)中 myViewStyle 的值 → @style/GreenStyle → 從 GreenStyle 取得 customColor 為綠色。
結論:defStyleAttr 的作用是——前兩層都撲空時,去 theme 的某個屬性看看它是否指向一個 style,若是,再從那個 style 取值。
第四個參數 defStyleRes 與 defStyleAttr 類似,都是前面幾層的補位,優先級最低。差別在於:defStyleRes 本身就是一個 style 資源 ID,而 defStyleAttr 需要透過 theme 屬性間接找到 style。
<style name="BlueStyle">
<item name="customText">customText in BlueStyle</item>
<item name="customColor">#FF0000FF</item>
</style>
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, 0, R.style.BlueStyle);
第三個參數為 0,第四個參數為 R.style.BlueStyle,最終呈現藍色文字:

需要注意:只有當 defStyleAttr 為 0,或該屬性在 theme 中找不到對應 style 時,才會啟用 defStyleRes。若 defStyleAttr 有效、但它指向的 style 沒有定義任何屬性值,defStyleRes 也不會被採用。
即使不使用 <declare-styleable> 也能定義 XML 屬性,但仍強烈建議把屬性收攏在該節點之下——因為 Android 會順帶在 R.styleable 中生成一批可直接使用的索引常量,省下大量硬編碼與出錯空間。
屬性取值的優先級,由高到低依序為:
layout 中直接賦值(AttributeSet) > View 的 style 屬性 > defStyleAttr > defStyleRes
把這條鏈路記住,自定義 View 的屬性行為就不再是一團黑盒。希望本文對你理解與實作自定義 XML 屬性有所幫助。
AOSP 編譯疑難雜症集中報:從 libz 到 JDK 的完整排查
第一次自行編譯 Android 原始碼,幾乎每個人都會撞上一串錯誤。以下把常見問題與對應解法整理成一份清單,遇到時直接對照處理。 一、cannot find -lz 錯誤
Android Metro 风格菜单实现思路及代码
Metro 风格(磁贴风格)以其简洁明快的方块布局广受欢迎。今天我们就来在 Android 平台上实现这样一个炫酷的 Metro 风格菜单效果。 实现思
Android 程式設計:實作圖片 3D 旋轉效果
本文分享一個在 Android 中實作圖片 3D 旋轉效果的實例,供大家參考。 接下來的示例要實作的是圖片的 3D 旋轉效果。 要做 3D 效果一般會想到 OpenGL,
自訂 View 實作:自由定製的優惠券邊緣背景
1、功能介紹 現在的購物類 App 真是多不勝數,經常能在裡面看到優惠券的身影。今天我們就來動手實作一個優惠券的背景效果。實務上若想偷懶,直接用一張背景圖當底就完工了,但