简体   繁体   中英

Change checkbox color when checked?

I would like to use the default checkbox in my app, but I only want the checkbox color to change to red when checked. I tried buttonTint, but it makes the box red when unchecked so that doesn't work.

A relatively easy way to do this would be to apply a theme just to your checkbox. Essentially you would add a style to your styles.xml resource file kind of like the below. Doing it this way you can even give a custom color to your checkbox when it is unchecked. However you can leave off the android:textColorSecondary if you would like to just use the black default checkbox.

styles.xml

//main style above add this below.
<style name="RedCheckbox">
    <item name="colorAccent">#FF0000</item> //color when checked
    <item name="android:textColorSecondary>#00FFFF</item> //color when unchecked.
</style>

Then you would need to apply this to your checkbox.

<CheckBox
    //rest of your checkbox setup
    android:theme="@style/RedCheckbox"  //this is the important line.
/>

You don't need to do anything programmatically it will simply change on the different states. This would be the result:

UNCHECKED

在此处输入图片说明

CHECKED

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM