简体   繁体   English

选中复选框时更改复选框颜色?

[英]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. 我尝试了buttonTint,但是当未选中时,它会使方框变成红色,因此不起作用。

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. 从本质上讲,您将向您的styles.xml资源文件中添加一种样式,如下所示。 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. 但是,如果您只想使用黑色默认复选框,则可以不使用android:textColorSecondary。

styles.xml 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 UNCHECKED

在此处输入图片说明

CHECKED CHECKED

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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