I am trying to add a color to the switches in Android Studio using Kotlin I tried few answers fronm this forum and couldn't get it to work
Is it possible to make this work programmatically?
CodePudding user response:
You can use this condition for kotlin. You should try this.
// condiotion while switch is on
if(mySwitch.isChecked){
mySwitch.setThumbResource(getColor(R.color.yourcolor))
mySwitch.setTrackResource(getColor(R.color.yourcolor))
}
// Condition while switch is off
else {
mySwitch.setThumbResource(getColor(R.color.yourcolor))
mySwitch.setTrackResource(getColor(R.color.yourcolor))
}
CodePudding user response:
The switch color follows the textColor
attribute. You can use setSwitchTextAppearance to change the textColor
.
From the same Switch
docs,
the textAppearance and the related setTypeface() methods control the typeface and style of label text, whereas the switchTextAppearance and the related setSwitchTypeface() methods control that of the thumb.
CodePudding user response:
If its a material switch
mySwitch.setTrackTintList("your_color")
mySwitch.setThumbTintList("your_color")
or like this
if (isChecked) {
mySwitch.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_true_color), PorterDuff.Mode.SRC_IN);
} else {
mySwitch.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_false_color), PorterDuff.Mode.SRC_IN);
}