【问题标题】:Change colorControlActivated color programmatically以编程方式更改 colorControlActivated 颜色
【发布时间】:2015-12-06 14:40:32
【问题描述】:

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

现在我用它来确定颜色。

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

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

【问题讨论】:

标签: android checkbox switchcompat


【解决方案1】:
    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
            }));

【讨论】:

  • 欢迎来到 Stack Overflow。请解释您在代码中所做的事情,以便其他人也可以从中受益。
【解决方案2】:

另一种做法,改变背景颜色:

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

【讨论】:

    【解决方案3】:

    其实不难。

    例子:

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

    【讨论】:

    • 像魅力一样工作!
    • 那绝对是完美而清晰的答案
    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多