use*_*993 11 java checkbox android 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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
问题是它没有改变正确的事情.关于如何改变这种颜色的任何想法?
yww*_*ynm 17
更换你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);
}
Run Code Online (Sandbox Code Playgroud)
sud*_*007 12
要为CompoundButton Tints着色,请尝试使用API> 21及以下.
if (Build.VERSION.SDK_INT < 21) {
CompoundButtonCompat.setButtonTintList(button, ColorStateList.valueOf(tintColor));//Use android.support.v4.widget.CompoundButtonCompat when necessary else
} else {
button.setButtonTintList(ColorStateList.valueOf(tintColor));//setButtonTintList is accessible directly on API>19
}
Run Code Online (Sandbox Code Playgroud)
Gab*_*ova -4
您是否尝试创建一个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>
Run Code Online (Sandbox Code Playgroud)
在您的布局文件中,将此文件应用于您的复选框
<CheckBox
android:id="@+id/myCheckBox"
android:text="My CheckBox"
android:button="@drawable/cb_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)
@drawable/checked和@drawable/unchecked是复选框的两张图像,因此您可以在其中添加您想要的颜色
或者不更改按钮布局,将此属性添加到您的复选框
android:buttonTint="@color/YOUR_CHECKMARK_COLOR_HERE"
Run Code Online (Sandbox Code Playgroud)