Change Checkbox colorAccent in runtime programmatically

xpto picture xpto · Mar 2, 2015 · Viewed 9.3k times · Source

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 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 in runtime: How to set colorAccent in code?

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

Thanks!

Answer

Amol Suryawanshi picture Amol Suryawanshi · Oct 24, 2016

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)