Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

改寫系統控件長相:拆解 RadioButton 的 style 與 selector

開發時常會發現系統控件的外觀與設計稿有一段差距。本文只討論「外觀」的替換,至於在系統控件上做功能擴充的客製化,是另一個主題。

先看系統是怎麼定義 RadioButton 的

RadioButton 長什麼樣子,取決於它的 background 與 button 屬性。Android 在源碼的 android/frameworks/base/core/res/res/values/styles.xml 中給了預設值:

<style name="Widget.CompoundButton.RadioButton">
    <item name="android:background">@android:drawable/btn_radio_label_background</item>
    <item name="android:button">@android:drawable/btn_radio</item>
</style>

也就是說,背景圖是 btn_radio_label_background,按鈕圖樣是 btn_radio。

btn_radio_label_background 位於 res/drawable-mdpi/ 下,是一張 NinePatch(.9.png)圖片,用來當背景並可自由拉伸填滿。

btn_radio 則是 res/drawable/btn_radio.xml,一個用 XML 定義的 drawable:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
        android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
        android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
        android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
        android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
        android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
        android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false"
        android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true"
        android:drawable="@drawable/btn_radio_on" />
</selector>

以其中一項為例:

<item android:state_checked="true" android:state_pressed="true"
      android:drawable="@drawable/btn_radio_on_pressed" />

意思是「被選中且被按下」時,按鈕要長成 btn_radio_on_pressed 的樣子,對應的圖檔是 res/drawable-mdpi/btn_radio_on_pressed.png。

若對 selector 不熟,可以翻 Android SDK 文件的 Dev Guide → Application Resources → Resource Types。item 可用的狀態屬性包含:

android:drawable="@[package:]drawable/drawable_resource"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"]

當控件狀態與某個 item 相符,就會採用該 item 指定的 drawable。

換外觀的兩個步驟

步驟一:製作 NinePatch 背景

準備一張 PNG(白色是否需透明看需求),執行 SDK 的 tools/draw9patch,在可伸縮區域四周畫上黑線,告知系統哪些部分可以拉伸。完成後圖片邊緣會多出黑線,這是正常現象。

步驟二:針對各狀態提供按鈕圖

例如可以規劃成:啟用且未選中是紫色外框;啟用且選中在框內多一個紅色中心點;按下時外框改為黃色;停用狀態則一律用灰色外框與灰色中心點。其餘較少見的狀態可自行增補。

小結

整個客製化其實就是「看懂 style 指向哪些資源 → 換掉 NinePatch 背景 → 用 selector 為每種狀態指定圖檔」。理解這條鏈路後,任何系統 CompoundButton 的外觀都能被替換。

Copyright © Linux教程網 All Rights Reserved