Bored of using the plain pre-defined switch design? Let’s see how we can change it.
The Switch or Toggle is a widget that defines the state of a button between 2 values: selected and not selected, although typically is used to define the ON/OFF state. On Android you can use:
SwitchCompat. From the Appcompat library, is a subclass of CompoundButton.
SwitchMaterial. From the Material library, extends from the SwitchCompat. [Update: deprecated from v1.7.1 to MaterialSwitch to follow naming convention of MaterialButton and MaterialCardView]
Anatomy of the switch:
But what if you don’t want the style that comes by default? What if you want to customize it? Well, let’s see how we can approach it:
Step 1: Add the switch to your activity/fragment xml
Step 2: Add a drawable for the track
Create a drawable file, let’s name it “switch_track”, add <selector> as its root element and here we’ll define 2 more drawables for its false and true state:
The true/false drawable states are going to be the similar, the difference will be the icons to display for each one of them (if you want a more sharped angles, you can remove the radius attribute):
For track_on.xml:
For track_off.xml:
Why do we add a layer-list on above examples? Because we want to shape the track and we want to add an image to it, so we would need for that a list of drawables represented by the <item> element.
Step 3: Add a drawable for the thumb
Same process as with the track, create the “switch_thumb” xml file and add the custom drawables with the <selector> as root element:
And let’s define the true/false states:
For thumb_on.xml:
For thumb_off.xml:
Step 4: Add your custom drawables to the switch
Now that we have created our xml files, we need to reference them in the switch through the attributes app:track and android:thumb:
It should look like this
Now you’re ready to customize it! Thanks for reading.
Comments