組合控件是自定義控件的一種,它並非直接繼承 View 從零繪製,而是把幾個原生控件拼裝起來,再對外提供一組設定接口。實務專案裡,只要同一段 UI 結構重複出現三次以上,就該考慮抽成組合控件。
自定義控件真正的價值在於「高內聚、低耦合」:把需要模組化的 UI 與邏輯打包在一起,對外只暴露必要的屬性與方法,內部細節不外洩。一個寫得好的控件就像一個封閉的小王國,規則由你制定,外部干預不了,維護成本自然下降。這與程式邏輯層做模組化其實是同一套思維。
要做的畫面底部是一排「圖片+文字」的入口,三個一組。這裡其實有兩層組合:單一的圖文單元(Item)是一層,三個 Item 排成的一整排又是外層控件。本文聚焦在 Item 本身。
Item 需要暴露的屬性包括:文字內容、文字顏色、文字大小、圖片來源、圖片背景、不透明度、圖片寬高。這些都宣告在 res/values/attr.xml 中,之後就能像使用原生控件一樣在 XML 裡設定。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LevelMenuItem">
<attr name="text" format="string" />
<attr name="text_color" format="color" />
<attr name="text_size" format="dimension" />
<attr name="image_src" format="reference" />
<attr name="image_bg" format="reference" />
<attr name="image_alpha" format="integer" />
<attr name="image_height" format="dimension" />
<attr name="image_width" format="dimension" />
</declare-styleable>
</resources>
檔案放在 values 目錄下,與 strings.xml 同層。format 決定該屬性的型別,常見的有 string、color、dimension、reference、integer、boolean、float 與 enum,依實際要傳入的值挑選即可。
建立 res/layout/level_menu_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/image_item"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter" />
<TextView
android:id="@+id/tv_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#23ffffff"
android:textSize="25sp" />
</LinearLayout>
留意 android:textColor="#23ffffff" 是八位:前兩位 23 是不透明度,後六位 ffffff 才是 RGB。在 Java 中同樣寫法如下:
setTextColor(0x23ffffff);
如果設計稿給的是百分比,例如「不透明度 30%」,換算方式是把 00~ff 對應十進位的 0~255,再乘以百分比:255 × 0.3 ≈ 76.5,取 76 轉成十六進位就是 4c,寫成 #4cffffff。
取得自定義屬性的標準流程是:先用 obtainStyledAttributes 搭配自訂的 styleable,逐項讀值後設定到子 View,最後別忘了呼叫 recycle() 釋放資源。
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LevelMenuItem);
String text = a.getString(R.styleable.LevelMenuItem_text);
int textColor = a.getColor(R.styleable.LevelMenuItem_text_color, 0xFFFFFFFF);
a.recycle();
完成後,在真正的版面檔裡就能像原生控件那樣宣告使用,並把重複的 UI 細節全部收攏到一個檔案中。
延伸閱讀:Android 專題頁面