Marcelo Idemax
Marcelo Idemax

Reputation: 2810

Change Checkbox colorAccent at runtime programmatically

I'm creating an ordinary Checkbox view:

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Enter image description here

This light green (#A5D6A7) is due the accent color defined in the main style:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorAccent">@color/green_light</item>

I already found that I can't change this style at runtime: How to set colorAccent in code?

I want to change this color on a specific Checkbox, not globally over the app. Can I do it without creating a specific asset? Because the user will able to change this color at runtime.

Upvotes: 15

Views: 10406

Answers (4)

Raja Jawahar
Raja Jawahar

Reputation: 6952

For an API level greater than or equal to Lollipop (21), try the below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    checkBox.buttonTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.color_rose))
}

Upvotes: 1

Manuel Schmitzberger
Manuel Schmitzberger

Reputation: 5468

This works for me:

public void setCheckBoxColor(CheckBox checkBox, int checkedColor, int uncheckedColor) {
     int states[][] = {{android.R.attr.state_checked}, {}};
     int colors[] = {checkedColor, uncheckedColor};
     CompoundButtonCompat.setButtonTintList(checkBox, new 
         ColorStateList(states, colors));
}

Upvotes: 7

Amol Suryawanshi
Amol Suryawanshi

Reputation: 2184

Below code will work smoothly without slowing down check and uncheck behavior of checkbox.because checkbox.setSupportButtonTintList(colorStateList); will behave unexpectedly on some devices

ColorStateList  colorStateList = new ColorStateList(
                        new int[][]{
                                new int[]{-android.R.attr.state_checked}, // unchecked
                                new int[]{android.R.attr.state_checked} , // checked
                        },
                        new int[]{
                                Color.parseColor("#cccccc"),
                                Color.parseColor("##cccccc"),
                        }
                );

 CompoundButtonCompat.setButtonTintList(checkBox,colorStateList)

Upvotes: 20

Renjith Thankachan
Renjith Thankachan

Reputation: 4336

Use AppcompatCheckbox

 AppCompatCheckBox acb = (AppCompatCheckBox)findViewById(R.id.acb);
 ColorStateList colorStateList = new ColorStateList(
                new int[][]{

                     new int[]{-android.R.attr.state_enabled}, //disabled
                     new int[]{android.R.attr.state_enabled} //enabled
                },
                new int[] {

                     Color.RED //disabled
                     ,Color.BLUE //enabled

                }
        );

  acb.setSupportButtonTintList(colorStateList);

Upvotes: 10

Related Questions