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

时间:2015-12-17 17:02:48

标签: java android checkbox colors

我在Android中使用CheckBox视图。我想在检查时更改它的颜色。现在它是默认的深绿色,当它被检查时,我想把它改成不同的东西,当没有检查时,只是默认的颜色。

这是我的代码:

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);
        }

    }
});

问题在于它没有改变正确的事情。关于如何改变这种颜色的任何想法?

enter image description here

4 个答案:

答案 0 :(得分:13)

CheckBox替换为AppCompatCheckBox并调用以下方法:

public static void setCheckBoxColor(AppCompatCheckBox checkBox, int uncheckedColor, int checkedColor) {
    ColorStateList colorStateList = new ColorStateList(
            new int[][] {
                    new int[] { -android.R.attr.state_checked }, // unchecked
                    new int[] {  android.R.attr.state_checked }  // checked
            },
            new int[] {
                    uncheckedColor,
                    checkedColor
            }
    );
    checkBox.setSupportButtonTintList(colorStateList);
}

答案 1 :(得分:9)

要为CompoundButton Tints着色,请尝试使用 API> 21及以下

wildfly

答案 2 :(得分:0)

implement this file in res 

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector>



and then add button to checkbox

<CheckBox android:layout_width="wrap_content"
 android:layout_height="wrap_content" 
 android:text="new checkbox"
 android:background="@drawable/checkbox_background" 
 android:button="@drawable/checkbox" />

答案 3 :(得分:-3)

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

//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>

在布局文件中将此文件应用于复选框

<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是您的复选框的两张图片,因此您可以放置​​一个您想要的颜色

或者不更改按钮布局,将此属性添加到复选框

android:buttonTint="@color/YOUR_CHECKMARK_COLOR_HERE"