问题描述
我想从 java 代码而不是从 xml 更改“开关”图标颜色,因为开关是动态创建的。 最小 SDK 是 16。非常感谢帮助。
Switch aSwitch = new Switch(context);
holder.llSwitch.addView(aSwitch);
holder.navIcon.setText(context.getResources().getString(R.string.fa_bell_o));
1楼
您可以检查按钮是否选中并使用状态设置颜色
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);
}
});
因为你搞砸了Switch
和ToggleButton
检查这个答案
编辑:仅对于拇指颜色更改,您可以尝试如下
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);
}
});