編輯:關於 Android 程式設計
只要寫過 Android 應用,你一定見過畫面上那些密密麻麻的 XML 屬性。這篇文章要談的,是這些屬性背後的機制:屬性從哪裡來、為什麼有些屬性用不了、自定義屬性怎麼定義與解析,以及樣式(Style)與主題(Theme)如何像網頁的 CSS 一樣,替你的介面建立一致的視覺語言。
所謂屬性,就是佈局檔裡那些 android: 開頭的設定。它們看似簡單,但每一個名稱其實都要經過編譯工具的層層檢查。
AAPT 是 Android Asset Packaging Tool,功能非常龐雜:解析 manifest、打包 assets 與 resources、驗證 XML 正確性。它是眾多負責「處理資源」的工具之一。
這些屬性在 View 的各個子類別文件中有記載,例如:
https://developer.android.com/reference/android/view/View.html
而它們真正的定義位置是:
$ANDROID_HOME/frameworks/base/core/res/res/values/attrs.xml
這套機制是為「擴充」而設計的:View 會直接忽略自己不認得的屬性,所以自定義屬性才有可能存在。
Android API 有白名單機制,而屬性名稱也包含在內。也就是說,只有當某個屬性被列進下面這份清單時,你才用得了它:
$ANDROID_HOME/frameworks/base/api/<n>.{xml, txt}白名單解釋了「為什麼這個標識符在 Java 端取不到」,但它並不能完全解釋「為什麼 aapt 也看不到它」——這一點我也還沒找到權威說明。
很多範例會寫成這樣,把顏色、邊距當成建構參數硬塞進去:
public abstract class FooView extends BarView {
private final int bgColor;
private final int fgColor;
private final int margin;
private final int padding;
protected FooView(int bgColor, int fgColor, int margin, int padding) {
this.bgColor = bgColor;
this.fgColor = fgColor;
this.margin = margin;
this.padding = padding;
}
}public class MyFooView extends BaseView {
public FooView(Context context) {
super(Color.RED, Color.GREEN, 7, 3);
}
}顯然,更好的做法是定義新的屬性,用它們來配置你的自定義控制項。

在 values 目錄下新增一個 attrs.xml:
接著在一個 declare-styleable 節點下宣告屬性。特別注意:declare-styleable 並不是命名空間,因此屬性名稱必須全域唯一。
<declare-styleable name="tag_view">
<attr name="tag_view_text">
<enum name="normal" value="0" />
<enum name="sans" value="1" />
<enum name="serif" value="2" />
<enum name="monospace" value="3" />
</attr>
</declare-styleable>目前共有十種格式。它們沒有正式文件,但都在 aapt 的原始碼裡有定義:
$ANDROID_HOME/frameworks/base/tools/aapt/ResourceTable.cpp
多種格式可以用「或」串接使用。不過大多數格式本身已經接受參考了,再加 reference 通常是多此一舉。列舉型別的寫法要注意,attr 節點內可以放多個 enum 子元素:
<attr name="my_flag">
<enum name="false" value="0" />
<enum name="true" value="1" />
</attr>public TagView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// #1 一定要讓父類先解析它自己的屬性
TypedArray atts = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.tag_view, defStyle, 0);
try {
final int n = atts.getIndexCount();
for (int i = 0; i < n; i++) {
try {
int attr = atts.getIndex(i);
switch (attr) {
case R.styleable.tag_view_tag_view_text_color:
textColor = atts.getColor(attr, textColor); // #3
break;
// ... 其他屬性
}
} catch (UnsupportedOperationException e) {
Log.w(TAG, "Failed parsing attribute: " + atts.getString(i), e);
} catch (NotFoundException e) {
Log.w(TAG, "Failed parsing attribute: " + atts.getString(i), e);
}
}
} finally {
atts.recycle(); // #4 用完記得回收
}
}四個重點:
1. 務必呼叫父類的建構子,讓父類有機會解析它自己的屬性。
2. 雖然可以硬從 AttributeSet 裡取值,但那是自找麻煩——樣式還沒被套用,@ 參照也還沒被解析。
3. TypedArray 針對上述格式都有對應的 getter,還多了幾個好用的方法,例如 getDrawable、getDimensionPixelOffset 等。
4. 使用完畢後一定要呼叫 recycle()。
如果屬性很多,一個常見的簡潔寫法是先給預設值,再逐案覆寫:
attribute = defaultVal;
// ...
case R.styleable.tag:
attribute = atts.getXXX(attr, attribute);
// ...
finalAttribute = attribute;屬性數量真的很多時,可以考慮引入 builder 模式。
先在佈局檔加上自定義命名空間,之後就能像系統屬性一樣使用:
xmlns:tagview="https://schemas.android.com/apk/res/<你的套件名稱>"
要注意:即使屬性是定義在函式庫專案裡,命名空間仍然要寫你自己 App 的套件名稱。
<net.callmeike.android.sandbox.tagview.TagView
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tagview="https://schemas.android.com/apk/res/net.callmeike.android.sandbox.tagview"
android:id="@+id/tags"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
tagview:tag_view_tag_drawable="@drawable/tag"
tagview:tag_view_tag_margin="20dp"
tagview:tag_view_tag_padding_horizontal="10dp"
tagview:tag_view_tag_padding_vertical="6dp"
tagview:tag_view_text_color="@color/green" />樣式替 Android UI 帶來了近似 CSS 的能力,語法非常簡單。它做的事,就是把佈局檔裡的:
android:attribute="value"
翻譯成樣式資源裡的:
<item name="android:attribute">value</item>
再以 style 屬性套用:注意 style 屬性不在 android 命名空間中。
原本寫成這樣:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/green"
android:textSize="64sp" />可以整理成這樣:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/big_green" /><style name="big_green">
<item name="android:textSize">64sp</item>
<item name="android:textColor">@color/green</item>
</style>以下兩種寫法的效果大致相同。第一種用「點」串接名稱:
<style name="Big">
<item name="android:textSize">64sp</item>
</style>
<style name="Big.Green">
<item name="android:textColor">@color/green</item>
</style>第二種用 parent 屬性明確指定:
<style name="Big">
<item name="android:textSize">64sp</item>
</style>
<style name="Big_Green" parent="Big">
<item name="android:textColor">@color/green</item>
</style>parent 屬性,「點」的寫法在這種情況行不通<style name="MyButton" parent="android:Widget.Button">
<item name="android:background">@drawable/button_bg</item>
</style>想快速替 App 換個樣子,最省事的做法之一就是給按鈕自訂背景:
<shape android:shape="rectangle">
<corners android:radius="5dp" />
<gradient
android:angle="90"
android:centerColor="@color/mist"
android:endColor="@color/mist"
android:startColor="@color/mist" />
<stroke
android:color="@color/charcoal"
android:width="2dp" />
</shape>所有內建樣式都記錄在:
https://developer.android.com/reference/android/R.style.html
定義於:
$ANDROID_HOME/frameworks/base/core/res/res/values/styles.xml
定義名稱中的「.」在 Java 與文件中會被轉為「_」,而其可見性同樣由白名單控制:
$ANDROID_HOME/frameworks/base/api/<n>.{xml, txt}主題其實就是一堆「已命名的參照」,你可以把它想成函式分派表。以下是 Theme.Holo 的一小段:
<!-- AlertDialog attributes --> <item name="alertDialogTheme">@android:style/Theme.Holo.Dialog.Alert</item> <item name="alertDialogStyle">@android:style/AlertDialog.Holo</item> <item name="alertDialogCenterButtons">false</item> <item name="alertDialogIcon">@android:drawable/ic_dialog_alert_holo_dark</item>
它替兩個樣式建立了別名,另外還有一個布林列舉與一個 drawable。
主題可以指派給個別的應用元件,系統會依主題來決定外觀。只要替元件掛上覆寫了屬性的主題,就能重新定義該元件內 UI 物件的外觀——甚至包含不是由該元件管理的 UI 物件——而且完全不需要多寫任何程式碼。
<style name="AppTheme.One">
<item name="android:background">@color/gatoraid</item>
</style>
<style name="AppTheme.Two">
<item name="android:background">@color/grapeaid</item>
</style>使用 ? 語法可以參照主題中的某個元素。Theme.Holo 定義了 buttonStyle,因此在佈局中可以這樣寫:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/push_me"
style="?android:attr/buttonStyle" />但務必小心:問號語法允許你寫出「能編譯、卻跑不起來」的東西,因為被參照的屬性必須真的存在於某個主題之中。
主題是讓介面適配不同設備的強力工具,而其中最實用的一點,莫過於用它來同時支援多個 Android 版本。

? 語法參照主題樣式總結來說:自定義屬性讓控制項可以被靈活配置,樣式讓屬性設定得以重複利用,主題則是整套命名的參照集合,能一次改變整個元件甚至整個 App 的視覺表現。三者由下而上堆疊,就是 Android UI 樣式系統的完整拼圖。
Lumia手機也能暢讀電子書:WiFi傳書實作
Lumia看電子書可用Anyview閱讀的WiFi傳書。開啟軟體選擇點我導書、WiFi傳書,取得IP位址後,在PC瀏覽器輸入並上傳txt檔。 手機與PC需在同一Wi-Fi
Android Application 類別入門(一):全域狀態與資源管理
在 Android 應用中,每當應用程式啟動,系統就會為它建立唯一的 Application 物件,並在整個程序生命週期內持續存在。若我們繼承 Application 類
Firebase 上手 for Android:分析、用戶認證與實時數據庫
移動應用要做大一點,幾乎繞不開後端:用戶身份驗證、多設備數據同步、行為統計。可自建服務器意味著要懂運維、懂數據庫、懂接口設計——而多數獨立開發者的技能樹恰好缺這一支。 好
Android熱補丁技術解析:dexposed 的 Hook 原理
本文整理自嵌入式企鵝圈原創團隊成員、阿裡資深工程師 Hao 的分享。上一篇《Android 無線開發的幾種常用技術》介紹了多種常見開發技術,其中熱補丁正被越來越多團隊採用