我正在使用一个标准的开关控制与全息。轻主题在ICS应用程序。

我想改变切换按钮的高亮或状态颜色,从标准的浅蓝色到绿色。

这应该很容易,但我似乎不知道该怎么做。


当前回答

要在不使用style. XML或Java代码的情况下更改Switch样式,您可以将Switch定制为布局XML:

<Switch
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:thumbTint="@color/blue"
        android:trackTint="@color/white"
        android:checked="true"
        android:layout_height="wrap_content" />

它的属性android:thumbTint和android:trackTint,允许你自定义颜色

下面是这个XML的可视化结果:

其他回答

如果你想通过编程改变开关组件颜色,请使用下面的代码:

    binding.switchCompatBackupMedia.thumbTintList =
                ColorStateList.valueOf(Color.parseColor("#00C4D3"))
            binding.switchCompatBackupMedia.trackTintList =
                ColorStateList.valueOf(Color.parseColor("#00C4D31F"))

创建自己的9-patch图像,并将其设置为切换按钮的背景。

http://radleymarx.com/2011/simple-guide-to-9-patch/

当开关状态改变时,我通过更新颜色过滤器解决了这个问题…

public void bind(DetailItem item) {
    switchColor(item.toggle);
    listSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                switchColor(b);
        }
    });
}

private void switchColor(boolean checked) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        listSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
        listSwitch.getTrackDrawable().setColorFilter(!checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
    }
}

改变轨道和拇指绘制的色调颜色。

switch.getThumbDrawable().setTint(ContextCompat.getColor(this,R.color.colorAccent));

switch.getTrackDrawable().setTint(ContextCompat.getColor(this,R.color.colorAccent));

你可以试试这个库,很容易改变颜色的开关按钮。 https://github.com/kyleduo/SwitchButton