萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android CheckBox 自定義圖片與尺寸:Selector + Style 完整方案

三步驟完成 CheckBox 樣式重構

1. 繪製狀態選擇器

res/drawable/checkbox_selector.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/checkbox_checked" />
    <!-- 未選中狀態 -->
    <item android:state_checked="false" android:drawable="@drawable/checkbox_unchecked" />
    <!-- 可選:按下、不可用等狀態 -->
    <item android:state_pressed="true" android:state_checked="true" android:drawable="@drawable/checkbox_checked_pressed" />
    <item android:state_pressed="true" android:state_checked="false" android:drawable="@drawable/checkbox_unchecked_pressed" />
    <item android:state_enabled="false" android:state_checked="true" android:drawable="@drawable/checkbox_checked_disabled" />
    <item android:state_enabled="false" android:state_checked="false" android:drawable="@drawable/checkbox_unchecked_disabled" />
</selector>

2. 定義 Style 統一尺寸與間距

res/values/styles.xml

<style name="CustomCheckBox" parent="Widget.AppCompat.CompoundButton.CheckBox">
    <item name="android:button">@drawable/checkbox_selector</item>
    <item name="android:buttonTint">@null</item> <!-- 禁用 Material 色調覆蓋 -->
    <item name="android:layout_width">24dp</item>
    <item name="android:layout_height">24dp</item>
    <item name="android:minWidth">24dp</item>
    <item name="android:minHeight">24dp</item>
    <item name="android:paddingLeft">8dp</item> <!-- 文字間距 -->
    <item name="android:scaleType">centerInside</item>
</style>

3. 佈局中套用

<CheckBox
    android:id="@+id/cb_agree"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="同意條款"
    style="@style/CustomCheckBox" />

進階:完全自定義 View (繼承 CompoundButton)

若需更精細控制 (如動畫、不規則形狀),可自建 CustomCheckBox extends AppCompatCheckBox 並覆寫 onDraw()。

MaterialCheckBox (Material Components 1.1+)

<com.google.android.material.checkbox.MaterialCheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Material 風格"
    app:buttonIcon="@drawable/checkbox_selector"
    app:useMaterialThemeColors="false" />

圖片資源建議

  • 提供 **mdpi/hdpi/xhdpi/xxhdpi/xxxhdpi** 五套圖,尺寸建議 24×24dp 基準 (mdpi 24px, hdpi 36px, xhdpi 48px...)。
  • 使用 **VectorDrawable (.xml)** 可無限縮放、APK 體積更小。
  • 留透明邊距 (如 2dp) 避免邊緣鋸齒。

常見問題

現象原因解決
圖片不顯示/被拉伸未設 `scaleType` 或 `buttonTint` 干擾加 `android:scaleType="centerInside"`、`buttonTint="@null"`
點擊區域過小圖片本身太小增大 `minWidth/minHeight` 或給父佈局 `padding`
狀態不切換Selector 缺少狀態項補齊 `state_checked=true/false` 至少兩項
copyright © 萬盛學電腦網 all rights reserved