In this tutorial, I will show you how to take control of a switch and change its appearance.
We can change the track and the thumb of our switch by creating new drawable objects.
Track
Below is an example code for the track.
switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<solid android:color="@color/salmon_pink"/>
<corners android:radius="1dp"/>
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="1dp"/>
</shape>
</item>
</selector>
We defined a selector that selects an appropriate object (one of two) depending on the switch state (android:state_checked).
Then it is needed to assign our newly created track to the switch.
We do that by putting this line of code in switch definition.
<androidx.appcompat.widget.SwitchCompat
...
app:track="@drawable/switch_track"/>
Thumb
It is very similar to changing track - creating a selector that shows the appropriate thumb depending on the switch state.
switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_thumb_unchecked" android:state_checked="false" />
<item android:drawable="@drawable/switch_thumb_checked" android:state_checked="true" />
</selector>
And below is an example code for thumb in checked switch.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/green" />
<corners android:radius="7dp" />
</shape>
</item>
<item
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
<corners android:radius="5dp"/>
<size android:height="30dp" android:width="60dp"/>
</shape>
</item>
</layer-list>
Passing thumb to the switch.
<androidx.appcompat.widget.SwitchCompat
...
android:thumb="@drawable/switch_thumb" />
The result
The possibilities are endless. You can create a switch that will perfectly fit your application.
Top comments (0)