Customizing Switch using XML

Android provides us with its default Switch, in particular SwitchCompat. By default it looks like below (enlarged). It uses the provided @color/colorAccent when turned on (checked).

Default SwitchCompat

However, I was tasked to make a custom version of it, that behave the same, but looks different, as below (enlarged)

I had to go through a bit of discovering to get it, purely using the XML. Hence share with all. Besides, it touches a little on custom Drawable, Color, Selector, Style, Theme, etc, on the XML. Hence a good overview bits of everything worth sharing.

The Switch Anatomy

To have a SwitchCompat, just add the code below in the layout

<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

As for the customized, it is just adding the Style as below

<android.support.v7.widget.SwitchCompat
style="@style/SwitchCompatStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

More detail on the style coming. But before that, let’s know the basic anatomy of…

--

--