以编程方式更改 colorControlActivated 颜色

Change colorControlActivated color programmatically

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

现在我用它来确定颜色。

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

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

其实做起来并不难

示例:

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));

另一种方法,更改背景颜色:

setBackgroundColor(android.graphics.Color.GREEN);

作为:

holper.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if (isChecked){

                buttonView.setBackgroundColor(android.graphics.Color.GREEN);
            }}
    DrawableCompat.setTintList(switch.getThumbDrawable(), new ColorStateList(
            new int[][]{
                    new int[]{android.R.attr.state_checked},
                    new int[]{}
            },
            new int[]{
                    Color.parseColor("Write Color code-for ex #ffffffff"),
                    Color.GRAY
            }));