Android 自定义CheckBox样式无效

2020-09-08  本文已影响0人  霁逸lei

先说结论,按网上的方式设置checkBox的button属性、background属性全部都失败了,然后发现在API19的模拟器上无法正常显示,在API26的真机上style样式正常显示,接着找低版本样式问题,然后发现了buttonCompat,设置一波,有效,链接如下。
https://blog.csdn.net/qq_36487432/article/details/104926509

1..写对应的selector文件

selector_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/img_checkbox_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/img_checkbox_unchecked"/>
</selector>

2.xml配置

 <!-- Compat attr to load backported drawable types -->
<attr format="reference" name="buttonCompat"/>

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="@dimen/y10"
    android:layout_height="@dimen/y10"
    app:buttonCompat = "@null"
    android:button="@drawable/selector_checkbox"
    android:background="@null"/>


====================可优化成如下模式====================
<CheckBox
    android:id="@+id/checkbox"
    style="@style/CustomCheckBox"/>

<style name="CustomCheckBox" parent="Widget.AppCompat.CompoundButton.CheckBox">
    <item name="android:layout_width">@dimen/y10</item>
    <item name="android:layout_height">@dimen/y10</item>
    <item name="android:background">@null</item>
    <item name="buttonCompat">@null</item>
    <item name="android:button">@drawable/selector_tining_delete_checkbox</item>
</style>

3.效果图,去掉buttonCompat 属性后显示默认方框样式


image.png
上一篇下一篇

猜你喜欢

热点阅读