美文网首页
Android:设置复选框 CheckBox 的颜色

Android:设置复选框 CheckBox 的颜色

作者: 栩檬 | 来源:发表于2022-11-24 19:11 被阅读0次

    问题

    如何设置复选框在不同状态的颜色?

    默认样式


    默认样式.png

    预期样式


    预期样式.png

    回答

    可以借助 CheckBoxandroid:theme 属性实现预期效果。

    步骤

    1. 在 res/values/colors.xml 文件中定义两种颜色,一种用于选中状态,另外一种用于未选中状态。
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="colorPrimary">#6200EE</color>
        <color name="color_999999">#999999</color>
        ...
    </resources>
    
    1. 在 res/values/styles.xml 文件中定义一个样式资源,colorControlNormal用于指定未选中时的颜色,colorControlActivated 用于指定选中后的颜色。
    <resources>
        ...
    
        <style name="CheckBox" parent="Theme.AppCompat.Light">
            <item name="colorControlNormal">@color/color_999999</item>
            <item name="colorControlActivated">@color/colorPrimary</item>
        </style>
    
    </resources>
    
    1. 在 res/layout 目录下的布局中文件中,为 CheckBox 控件设置 android:theme 属性的值,引用在第 2 步中定义的样式资源。
    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
            ...
            <CheckBox
                  android:id="@+id/single_cb_football"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="足球"
                  android:textColor="@color/color_333333"
                  android:textSize="@dimen/text_size4"
                  android:theme="@style/CheckBox" />
            ...
    </layout>
    

    参考资料

    嘤嘤嘤999 : Android CheckBox修改选中状态框内部颜色及样式

    代码

    XuMeng-0/android-study

    相关文章

      网友评论

          本文标题:Android:设置复选框 CheckBox 的颜色

          本文链接:https://www.haomeiwen.com/subject/bqyxfdtx.html