Android 解决自定义 CheckBox 样式时的背景显示异常问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuwan1992/article/details/80815226
  1. 首先创建自定义样式文件

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/public_checkbox_select" android:state_checked="true" />
        <item android:drawable="@drawable/public_checkbox_normal" />
    </selector>
    
  2. 通过 CheckBox 的 android:button 属性设置样式时,在低版本设备上,原始的 CheckBox 背景仍会占据空间,导致 CheckBox 占据的空间比按钮图片大。如果设置 android:background="@null" 去除原始背景,又会导致 CheckBox 长宽为零不展示。

  3. 考虑直接用 android:background 属性设置样式,并设置 android:button="@null"。结果显示的按钮图片被拉伸。

  4. 研究 api 发现另一种途径,使用 android:drawableLeft 属性设置样式,并设置 android:background="@null"android:button="@null",最终解决问题。xml 文件如下:

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:button="@null"
        android:checked="true"
        android:drawableLeft="@drawable/checkbox_selector" />
    

猜你喜欢

转载自blog.csdn.net/liuwan1992/article/details/80815226
今日推荐