Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change colorControlActivated color programmatically

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?

like image 371
JR Tan Avatar asked Sep 10 '15 10:09

JR Tan


1 Answers

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));
like image 196
dtx12 Avatar answered Oct 16 '22 06:10

dtx12