当前位置: 代码迷 >> Android >> 从 Java 代码更改开关图标颜色
  详细解决方案

从 Java 代码更改开关图标颜色

热度:45   发布时间:2023-08-04 10:49:13.0

我想从 java 代码而不是从 xml 更改“开关”图标颜色,因为开关是动态创建的。 最小 SDK 是 16。非常感谢帮助。

    Switch aSwitch = new Switch(context);
    holder.llSwitch.addView(aSwitch); 
    holder.navIcon.setText(context.getResources().getString(R.string.fa_bell_o));

您可以检查按钮是否选中并使用状态设置颜色

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
Switch mySwitch = new Switch(this);
linearLayout.addView(mySwitch);
mySwitch.setBackgroundColor(Color.BLACK);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked)
            buttonView.setBackgroundColor(Color.RED);
        else buttonView.setBackgroundColor(Color.BLACK);
    }
});

因为你搞砸了SwitchToggleButton检查这个答案

编辑:仅对于拇指颜色更改,您可以尝试如下

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
final Switch mySwitch = new Switch(this);
linearLayout.addView(mySwitch);
mySwitch.getThumbDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked)
            mySwitch.getThumbDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
        else
            mySwitch.getThumbDrawable().setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY);
    }
});
  相关解决方案