如何更改复选框选中的颜色编程 [英] How to change checkbox checked color programmatically
问题描述
我在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?
推荐答案
您尝试创建选择器
并将此选择器
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
android:buttonTint="@color/YOUR_CHECKMARK_COLOR_HERE"
这篇关于如何更改复选框选中的颜色编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!