ZOFTINO.COM

Android Switch Button and Custom Switch Examples

This post shows how to use android switch button, apply material styles, create custom styles, create custom switch button and how to handle switch button click events.

Android Switch XML Element

 <Switch
    android:id="@+id/switch_one"
    android:layout_marginTop="16dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Switch One"
    /> 

Android Switch Properties

Some of the important switch properties are textAppearance, textColor, track, thumb, switchTextAppearance, textOn, testOff, background, and showText.

Property thumb is used to set a drawable that switches back and forth, property track is used for setting a drawable as track for switch thumb, textOn and textOff are used to set text to be displayed when switch is in on or off state, textswitchTextAppearance is used to set style for switch text, and showText is used to indicate whether to show switch text or not.

Android Switch Material Style

Android system provides many material themes. When application level theme is set to one of the material themes, android switch will be displayed applying default switch material theme of the application theme used in the application. Below screen shot shows switch button in both on and off states when application theme is set to Theme.AppCompat.

android switch button material style example

Android Switch Button Custom Style Application Level

Application level themes can be customized by setting properties to custom values. If you customize properties related to UI controls, the changes will be applied to all UI controls and throughout the application. To change switch text color and switch button color, you need to set textColorPrimaryDisableOnly and colorAccent properties to custom values.

Below theme is an example of custom application theme added to res/values/styles.xml file. You can apply it to an application by setting theme attribute of application element in mainifest xml file.

<style name="CustomAppTheme" parent="Theme.AppCompat">
    <item name="android:textColorPrimaryDisableOnly">#00838f</item>
    <item name="colorAccent">#e91e63</item>
</style>

Below screen shot shows switch button after application theme is set to custom material theme defined above.

android switch button material style custom color example

Android Switch Custom Style Individual

If you want to change switch style only in a particular section of your application, then define custom switch widget style by inheriting Widget.AppCompat.CompoundButton.Switch as shown below and apply it to switch elements using theme attribute.

Switch attribute colorControlActivated can be used to set track and thumb color when switch is active and colorForeground can be used to set track color when switch is in normal state.

<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
    <item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
    <item name="android:colorControlActivated">#1b5e20</item>
    <item name="android:colorForeground">#f57f17</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>

You can use thumbTint and trackTint properties to change color of thumb and track. Applying colors to track and thumb using selector xml allows you to apply different colors for different states, see custom switch section.

Android Switch Event Listener

Switch on and off events or switch drag event can be handled in two ways. One way of handling switch click event is by defining a method in your activity or fragment with View as input parameter and setting it as value for onClick attribute of Switch in layout xml as shown below.

public void processSwitchEvent(View view) {
    Toast.makeText(ToggleButtonActivity.this,
            "Switch event", Toast.LENGTH_SHORT).show();
}
<Switch
    android:id="@+id/switch_two"
    . . .
    android:onClick="processSwitchEvent"/>

Second way of handling switch on/off event is by defining OnCheckedChangeListener and adding it to switch button by using setOnCheckedChangeListener method.

Switch switchOne = (Switch) findViewById(R.id.switch_one);

switchOne.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(ToggleButtonActivity.this,
                            "Switch On", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ToggleButtonActivity.this,
                            "Switch Off", Toast.LENGTH_SHORT).show();
                }
            }
        });

Custom Switch Button

Android switch with custom track

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.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="center_vertical|fill_horizontal"
        android:start="4dp"
        android:end="4dp">
        <shape android:shape="rectangle"
            android:tint="@color/switch_color">
            <corners android:radius="2dp" />
            <solid android:color="@color/switchTrack" />
            <size android:height="20dp" />
        </shape>
    </item>
</layer-list> 

Below xml, used as switch_color in the above drawable, is color selector for track. Color is applied based on the state of switch. This file needs to be saved in res/color folder.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false"
        android:color="@color/switchTrackDisable"/>
    <item android:state_checked="true"
        android:color="@color/switchTrackActive" />
    <item android:color="@color/switchTrackNormal" />
</selector> 

Below xml shows applying the custom track drawable to Switch.

<Switch
    android:id="@+id/switch_oneone"
    . . .
    android:track="@drawable/switch_track_custom"/> 

Output of custom track of switch.

android switch with custom track example

Android switch with custom thumb

Android switch thumb can be customized by using material icon and defining drawable xml resource.

To do that, first download one of the android material icons which you want to use in your application or use any other image you may have and save it in res/drawable folder.

Then define drawable xml resource as shown below in res/drawable folder, our example file name is switch_thumb_custom.xml. This xml uses the above downloaded icon, defines shape and sets colors. To apply this to a switch, set its thumb attribute to the drawable xml.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/switchTrackNormal" />
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/switch_color" />
        </shape>
    </item>
    <item android:width="40dp"
        android:height="40dp">>
        <bitmap android:src="@drawable/brightness"
            android:tint="@color/switchThumbBgActive" />
    </item>
</layer-list> 

In the above xml switchTrackNormal and switchThumbBgActive are colors defined in res/values/colors.xml

 <?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="switchTrack">#ffd600</color>
<color name="switchTrackDisable">#90caf9</color>
<color name="switchTrackActive">#1565c0</color>
<color name="switchTrackNormal">#90caf9</color>
<color name="switchThumbBgActive">#1b5e20</color>
<color name="switchThumbActive">#ad1457</color>
<color name="switchThumbkNormal">#64b5f6</color>
</resources> 

Below color selector xml saved as switch_color.xml is used in the custom thumb drawable xml defined above.

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
    android:color="@color/switchTrackDisable"/>
<item android:state_checked="true"
    android:color="@color/switchThumbActive" />
<item android:color="@color/switchThumbkNormal" />
</selector> 

Below switch element in layout xml uses above custom switch thumb and switch track.

<Switch
    android:id="@+id/switch_one"
    . . .
    android:track="@drawable/switch_track_custom"
    android:thumb="@drawable/switch_thumb_custom"/> 

With switch button track customization explained from above section and switch button thumb customization explained in this section, the custom switch button will appear as shown below in normal and active states.

android switch with custom thumb example