Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 Android Checkbox 外觀的簡便做法

編輯:關於 Android 程式設計

Checkbox 是列表和表單裡的高頻控件,但系統默認樣式在不少場景下並不合適——早期版本看著樸素,放在有設計語言的界面裡更是顯得格格不入。好在換外觀比想象的簡單,改個 XML 就夠了。

準備素材

兩張圖:一張選中態,一張未選中態。本文以 checked.png 和 unchecked.png 為例,放進 drawable 目錄。

定義 selector

在 drawable 下新建 custom_checkbox.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android" >

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

    <item android:state_checked="false"
          android:drawable="@drawable/unchecked" />

    <item android:drawable="@drawable/unchecked" /><!-- 默認項 -->

</selector>

這裡用的是 state_checked 而不是 state_pressed,兩者含義完全不同:前者對應複選框本身的勾選狀態,後者對應手指按下。寫錯了會表現為「點下去有反應,勾選後沒變化」。

最後那個不帶狀態的 item 是兜底項,防止某些未預期的狀態下沒有圖可畫。

應用到控件

把 android:button 指向自定義的 selector:

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox" />

幾個實踐建議

如果還想改文字的外觀(顏色、大小隨勾選變化),可以再用 android:textColor 配一個 color selector,並通過 android:buttonTint 之外的途徑配合處理。

更規範的做法是把這套配置封進一個自定義樣式,然後在 Theme 裡通過 android:checkboxStyle 全局生效,這樣就不必每個 CheckBox 都重複寫一遍屬性。

另外,從 Android 5.0 起系統提供了 CheckBox 的 Material 主題版本,並支持通過 app:buttonTint 直接染色矢量圖標。如果你的 minSdk 允許,用 vector drawable 配合 tint 遠比準備多套 PNG 更省包體,也天然適配各種屏幕密度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved