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

Change switch icon color from java code

我想从 java 代码而不是 xml 更改 'switch' 图标颜色,因为开关是动态创建的。 最小 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 检查这个答案 Switch vs toggle

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

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