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.
Here's my code:
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?
Use the accent-color property to change the checkbox color in CSS.
If you want to change checkbox color then "colorAccent" attribute will use for checked state and "android:textColorSecondary" will use for unchecking state. "actionOverflowButtonStyle" will use for change the color of overflow icon in the Action bar. Same is for refresh button which i am using in my app.
This example demonstrates how do I change the color of the check box in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
So, the method to know if the check box is checked is : (CheckBox) yourCheckBox. isChecked() it returns true if the check box is checked.
To tint the CompoundButton Tints try this, for Both the API>21 and below.
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
}
Replace your CheckBox
with AppCompatCheckBox
and call following method:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With