You can check button is checkd or not and set the color with the state
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);
}
});
Since you are messing up with Switch
and ToggleButton
check this answer Switch vs toggle
Edit : Only for thumb color change you can try like below
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);
}
});