如何以编程方式更改复选框选中的颜色

如何以编程方式更改复选框选中的颜色

本文介绍了如何以编程方式更改复选框选中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 中使用 CheckBox 视图.当它被选中时,我想改变它的颜色.现在它是选中时的默认深绿色,我想将其更改为不同的颜色,如果未选中,则为默认颜色.

I'm using the CheckBox view in Android. I would like to change the color of it when its checked. Right now its that default dark green color when its checked and I would like to change it to something different and when not checked, just be the default colors.

这是我的代码:

CheckBox c = new CheckBox(this);
c.setId(View.generateViewId());

c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(buttonView.isChecked())
        {
            buttonView.setBackgroundColor(Color.rgb(64, 131, 207));
        }
        if(!buttonView.isChecked())
        {
            buttonView.setBackgroundColor(Color.WHITE);
        }

    }
});

问题在于它并没有改变正确的事情.关于如何更改此颜色的任何想法?

The problem is that it does not change the right thing. Any ideas on how to change this color?

推荐答案

您是否尝试创建 selector 并将此 selector 分配给您的 CheckBox像这样例如:

Did you try to create a selector and assign this selector to your CheckBox like this for example:

//drawable file called cb_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/checked" />
    <item android:state_checked="false" android:drawable="@drawable/unchecked" />
</selector>

在您的布局文件中将此文件应用到您的复选框

In your layout file apply this file to your checkBox

<CheckBox
    android:id="@+id/myCheckBox"
    android:text="My CheckBox"
    android:button="@drawable/cb_selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

@drawable/checked@drawable/unchecked 是你的复选框的两张图片,所以你可以在那里放一个你想要的颜色

@drawable/checked and @drawable/unchecked are two images of your checkbox, so you could put there a color that you want

或不改变按钮布局,将此属性添加到您的复选框

OR without changing the button layout, with adding this attribute to your checkbox

android:buttonTint="@color/YOUR_CHECKMARK_COLOR_HERE"

这篇关于如何以编程方式更改复选框选中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:23