Thursday, March 12, 2020

Custom Switch using XML Android Example

You can customize android switch track by defining a drawable xml resource as shown below. You need to save it in res/drawable folder, our example file name switch_track_custom. xml, and apply it to switch by using track attribute.
Custom Switch using XML Android Example

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"/>
Most reference would guide us to change the colorControlActivated. One define the theme as below
<style name="SwitchCompatTheme" >
    <item name="colorControlActivated">@color/pure_red</item>
</style>
Then have your SwitchCompat have the theme as below.
<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/SwitchCompatTheme" />
Changing the color specifically
In my case, I would like the track to be pure_red as well when checked, and grey when it is not checked. Hence I set a track color selector file name as switch_color.xml in the res/color folder.
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/pure_red"
          android:state_checked="true" />
    <item android:color="@color/grey"/>
</selector>
And set the color for the SwitchCompat’s thumb and track through the Style in style.xml
<style name="SwitchCompatStyle" >
    <item name="thumbTint">@color/switch_color</item>
    <item name="trackTint">@color/switch_color</item>
</style>
Then define your SwitchCompat view by setting the appropraite Style
<android.support.v7.widget.SwitchCompat
    style="@style/SwitchCompatStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
With this, you’ll get the track color as intended (ok, ok,I know having the same color for thumb and track looks ugly… it is fixed in the next section)

No comments:

Post a Comment