以编程方式更改colorControlActivated颜色

JR *_*Tan 11 checkbox android switchcompat

我已经阅读了一些关于颜色的线程,但是所有这些都必须通过style.xml进行设置.

现在我用它来确定颜色.

<style name="Color1SwitchStyle">
    <item name="colorControlActivated">#0e8488</item>
</style>'
Run Code Online (Sandbox Code Playgroud)

是否可以在不使用XML的情况下更改SwitchCompat/Checkbox的颜色,例如使用代码?

dtx*_*x12 47

实际上,这并不难.

例:

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));
Run Code Online (Sandbox Code Playgroud)