RadioButton改变圆圈颜色、CheckBox改变框的颜色

1,079 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

当时项目中多次涉及到单选框、多选框,又觉得默认颜色有些丑,就打算换一换颜色,网上看了好多文章,在我的项目中都不能改变单选框多选框的颜色,后来经过不断尝试,终于实现了改变单选框,多选框的颜色,特此做了总结。以后在遇到这样的问题就不至于不断尝试啦!废话就不多说了,直接看代码吧(有些方法和项目版本可能也有一定的关系)

首先是RadioButton的默认颜色更改:

第一种:在style里面写一个style

<style name="MyRadioButton" parent="Theme.AppCompat.Light">
        <item name="colorControlNormal">@color/colorPrimary</item>
        <item name="colorControlActivated">@color/colorAccent</item>
    </style>

然后布局里面引用这个style样式,记住一定要用属性一定要用theme,style不行哦。

<RadioGroup
        android:id="@+id/rg_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/rb_one"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="女"
            android:theme="@style/MyRadioButton"
            />

        <RadioButton
            android:id="@+id/rb_two"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="男"
            android:theme="@style/MyRadioButton" />

        <RadioButton
            android:id="@+id/rb_three"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="男"
            android:theme="@style/MyRadioButton" />

        <RadioButton
            android:id="@+id/rb_four"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="男"
            android:theme="@style/MyRadioButton" />
    </RadioGroup>

第二种:仅适用于api level 21或更高版本

<RadioButton
            android:id="@+id/rb_one"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="女"
            android:buttonTint="@color/your_color"
            />

在res--->values--->color里面写

<color name="your_color">#e75748</color>

第三种:图片选择器

drawable里面新建一个选择器,这种方法我并没有进行测试,使用的时候可以测试一下

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

    <item android:state_selected="true" android:drawable="@mipmap/tright"/>
    <item android:state_selected="false" android:drawable="@mipmap/tright"/>
    
</selector>

其次就是CheckBox默认颜色的更改:

这个和RadioButton一样,注意用theme,用style改变不了颜色

 <CheckBox
            android:id="@+id/cb_three"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="男"
            android:theme="@style/MyCheckBox"
            android:textColor="@color/view_title_text"/>

style文件里面:

<style name="MyCheckBox" parent="Theme.AppCompat.Light">
        <item name="colorControlNormal">@color/grey</item>
        <item name="colorControlActivated">@color/mediumturquoise</item>
    </style>

图片选择器的方法CheckBox应该也一样适用

欢迎大佬多多指教!