Implementing Custom Switch on Android
Implementing a custom Switch on a preliminary level includes changing the color overlay of the checked and unchecked state, on a more advanced level, we can completely change the appearance of the switch.
This is an example of a custom switch in Cuddle.AI application:-

In this, we are changing the thumb and the track component of the switch. For people who are unclear with these terms, the Track is part of the switch where it slides and the Thumb is the component that slides on the track.

To start with changing the switch, we begin with creating a new Kotlin class that inherits the “Switch” class of android.widget. Also, make the default constructors of the class.
class CarouselGridSwitch : Switch {internal var context: Context constructor(context: Context) : super(context) {
this.context = context
} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
this.context = context
} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
this.context = context
}}
Next, we need to change track and thumb drawable to make them look like our design. For this, we will be using 2 public functions of the Switch class.
For replacing the ThumbDrawable, we use
public void setThumbDrawable(Drawable thumb)For replacing the TrackDrawable, we use
public void setTrackDrawable(Drawable track)Usage: I recommend calling these functions in a try-catch block as they will give you a Null-Pointer exception on startup, the usage is shown in the snippet below
override fun setChecked(checked: Boolean) {
super.setChecked(checked)
changeSwitchAppearance(checked)
}private fun changeSwitchAppearance(isChecked: Boolean) { if (isChecked) {
try {
thumbDrawable = ContextCompat.getDrawable(context, R.drawable.ic_carousel_thumb)
trackDrawable = ContextCompat.getDrawable(context, R.drawable.ic_grid_carousel_track)
} catch (e: Exception) {
e.printStackTrace()
} } else {
try {
thumbDrawable = ContextCompat.getDrawable(context, R.drawable.ic_grid_thumb)
trackDrawable = ContextCompat.getDrawable(context, R.drawable.ic_grid_carousel_track)
} catch (e: Exception) {
e.printStackTrace()
}
}
}



As a final touch, add a call to your Switch’s “setChecked” function from the fragment or activity where you are setting it.
grid_carousel_switch.isChecked = falseVoila! you are done!

