編輯:關於 Android 程式設計
做 Android 開發久了,你一定會遇到這種情況:系統提供的控制項怎麼調都達不到設計稿的效果,於是只能自己動手寫一個自定義 View。而一旦開始自定義,下一個問題就跟著來了——怎麼讓這個 View 擁有屬於自己的屬性?本文就把這條路從頭到尾走一遍。
想像你寫了一個 CustomTextView,除了文字本身,你還希望能單獨指定它的文字顏色與文字大小。如果沿用系統屬性,就只能透過程式碼動態設定,寫法既不直觀,也無法在 Layout Editor 裡即時預覽。這時候,定義一組專屬屬性就是最自然的解法。
在 res/values/ 目錄下新增一個 attrs.xml,用 declare-styleable 標籤把同一組的屬性打包起來:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- resource 是根標籤,裡面可以定義多個 declare-styleable -->
<declare-styleable name="custom_view">
<!-- name 定義了這組樣式(styleable)的名稱 -->
<attr name="custom_color" format="color"></attr>
<!-- 每一個 attr 都要透過 format 指定型別 -->
<attr name="custom_size" format="dimension"></attr>
</declare-styleable>
</resources>
小技巧:如果同一個屬性想同時接受多種寫法,可以用 format="color|reference" 這種「或」的語法。
屬性宣告好之後,Android 會自動幫你在 R.styleable 底下產生對應的常數。接著在帶有 AttributeSet 參數的建構子裡,用 TypedArray 把它們讀出來:
public class CustomTextView extends TextView {
private int textSize; // 自定義文字大小
private int textColor; // 自定義文字顏色
// 使用自定義屬性時,會呼叫帶兩個參數的建構子
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// 取得 TypedArray 屬性物件
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_view);
// 從屬性物件中取出對應的值,第二個參數是預設值
textSize = ta.getDimensionPixelSize(R.styleable.custom_view_custom_size, 20);
textColor = ta.getColor(R.styleable.custom_view_custom_color, 0x0000ff);
setColorAndSize(textColor, textSize);
ta.recycle(); // 用完記得回收
}
public CustomTextView(Context context) {
super(context);
}
private void setColorAndSize(int textColor, int textSize) {
setTextColor(textColor);
setTextSize(textSize);
}
}
這裡有兩個容易忽略的細節:一是取值時一定要給預設值,因為使用者很可能根本沒在 XML 裡寫這個屬性;二是 recycle() 別忘了呼叫,TypedArray 是共用資源,用完歸還是好習慣。
先在根節點宣告自定義的命名空間(namespace 後面接的是你的應用程式包名),再用「前綴:屬性名」的方式寫入:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:ldm="https://schemas.android.com/apk/res/com.ldm.learn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f6f6f6"
android:orientation="vertical"
android:padding="10dp">
<com.ldm.learn.CustomTextView
android:layout_width="100dp"
android:layout_height="100dp"
android:text="自定義 TextView"
ldm:custom_color="#333333"
ldm:custom_size="35sp" />
</LinearLayout>
佈局說明:

xmlns:ldm 這一行是自定義屬性得以生效的關鍵:ldm 是前綴,可以任取名稱;而 https://schemas.android.com/apk/res/ 之後必須接「你的套件名稱」。寫錯了,XML 就會在編譯階段直接報錯。
三步驟就能完成自定義屬性:宣告 attrs.xml → 在 View 中用 TypedArray 取值 → 在佈局中透過自訂命名空間引用。把顏色、尺寸、樣式這類參數抽成屬性之後,同一個 View 就能在不同頁面重複使用,而不必為了差異去改程式碼,這是自定義控制項最實用的價值所在。
Android WebView 基本用法:與原生代碼雙向通信實踐
一直覺得把 Web 技術和 Android 原生組件結合起來做應用有事半功倍的效果,HTML5 普及之後更是如此——對原本做 Web 開發的同學來說,這幾乎是最短的一條入
Android RadioButton 與 RadioGroup 使用方法
RadioButton 與 CheckBox 差異RadioButton 通常用於單選情境。單顆 RadioButton 選取後無法再點擊取消;同一組 RadioGrou
Android 動畫:讓齒輪永不停歇地轉動
很多 loading 或裝飾性動畫裡都會用到「轉個不停的齒輪」效果。實現起來其實很簡單,用 RotateAnimation 就能讓齒輪無限勻速旋轉。 (這裡是靜態圖,實
一個萬能 BaseAdapter,搞定兩個 ListView 復用
做 Android 開發時,我們經常會遇到一個頁面裡出現多個 ListView、且數據類型各異的情況。如果為每個列表都寫一個 Adapter,代碼會變得冗餘難維護。本文就