Change colorControlActivated color programmatically

JR Tan picture JR Tan · Sep 10, 2015 · Viewed 11.7k times · Source

I have read a few threads regarding the color, but all of them has to set via style.xml.

For now I'm using this to determine the color.

<style name="Color1SwitchStyle">
    <item name="colorControlActivated">#0e8488</item>
</style>'

Is it possible to change the color of a SwitchCompat/Checkbox without using XML, for instance using code?

Answer

dtx12 picture dtx12 · Sep 16, 2015

Actually, it's not hard to do.

Example:

int[][] states = new int[][] {
        new int[] {-android.R.attr.state_checked},
        new int[] {android.R.attr.state_checked},
};

int[] thumbColors = new int[] {
        Color.BLACK,
        Color.RED,
};

int[] trackColors = new int[] {
        Color.GREEN,
        Color.BLUE,
};

SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switchControl);
AppCompatCheckBox checkBox = (AppCompatCheckBox) findViewById(R.id.checkbox);
checkBox.setSupportButtonTintList(new ColorStateList(states, thumbColors));
DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getThumbDrawable()), new ColorStateList(states, thumbColors));
DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getTrackDrawable()), new ColorStateList(states, trackColors));