Tutorial #100: The Switch from KitKat to Lollipop!

Hey everyone!

The new Android version release has brought few changes in the way developers used certain widgets to create layouts. For instance, starting from Lollipop, Android introduces a new Toolbar widget. As mentioned by Chris Banes in this post, the Toolbar widget is a generalization of the Action Bar pattern that gives developers much more control and flexibility. Similarly, Android has made a “switch” in the way the current Switch widget is implemented.

As mentioned on the developer’s page, a Switch is a two-state toggle switch widget that can select between two options. The user may drag the “thumb” back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox. Through this tutorial, we will learn how to implement the Switch widget in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create a new Activity class called TestSwitchActivity in any of your existing Android projects and write the following code,

TestSwitchActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;

public class TestSwitchActivity extends Activity {

	private TextView m_tvSwitchStatus;
	private Switch m_objSwitch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_switch);

		m_tvSwitchStatus = (TextView) findViewById(R.id.switchStatus);
		m_objSwitch = (Switch) findViewById(R.id.sampleSwitch);

		//set the switch to ON 
		m_objSwitch.setChecked(true);
		//attach a listener to check for changes in state
		m_objSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				if(isChecked){
					m_tvSwitchStatus.setText("Switch is currently ON");
				}else{
					m_tvSwitchStatus.setText("Switch is currently OFF");
				}

			}
		});

		if(m_objSwitch.isChecked()){
			m_tvSwitchStatus.setText("Switch is currently ON");
		}
		else {
			m_tvSwitchStatus.setText("Switch is currently OFF");
		}
	}
}

Step 2: Create Switch widget

In previous versions of Android, we would implement a Switch widget in our layout as follows,

activity_switch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <Switch
        android:id="@+id/sampleSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:text="@string/action" />

    <TextView
        android:id="@+id/switchStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sampleSwitch"
        android:layout_marginTop="22dp"
        android:text="@string/status"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

According to recent changes, the Switch widget can now be implemented using SwitchCompat. The difference is that it does not make any attempt to use the platform provided widget on those devices which it is available normally.

activity_switch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" >

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/sampleSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:text="@string/action"
        android:thumb="@drawable/thumb_pressed"
        android:track="@drawable/bg"/>

    <TextView
        android:id="@+id/switchStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sampleSwitch"
        android:layout_marginTop="22dp"
        android:text="@string/status"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

In this case, our Activity file would be as follows,

TestSwitchActivity.java

package com.app.lollipop.test;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class TestSwitchActivity extends Activity {

	private TextView m_tvSwitchStatus;
	private SwitchCompat m_objSwitch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_switch);

		try {

			m_tvSwitchStatus = (TextView) findViewById(R.id.switchStatus);
			m_objSwitch = (SwitchCompat)findViewById(R.id.sampleSwitch);
			m_objSwitch.setThumbResource(R.drawable.apptheme_switch_thumb_holo_light);
			m_objSwitch.setTrackResource(R.drawable.apptheme_switch_track_holo_light);
			m_objSwitch.setTextOn("ON");
			m_objSwitch.setTextOff("OFF");
			
			//set the switch to ON 
			m_objSwitch.setChecked(true);
			//attach a listener to check for changes in state
			m_objSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {

					if(isChecked){
						m_tvSwitchStatus.setText("Switch is currently ON");
					}else{
						m_tvSwitchStatus.setText("Switch is currently OFF");
					}

				}
			});

			if(m_objSwitch.isChecked()){
				m_tvSwitchStatus.setText("Switch is currently ON");
			}
			else {
				m_tvSwitchStatus.setText("Switch is currently OFF");
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.i("App", "Error occurred due to" +e.getMessage());
		}
	}
}

Finally, save all changes and run the Android application project on an emulator or a real device. If no errors occur then you should see the following output!

Android Switch on Pre Lollipop versions

Android Switch on Pre Lollipop versions

Android Switch on Lollipop

Android Switch on Lollipop

From here on, we will learn more about the recent changes in Android 5.0. We will also try to implement the same in the upcoming tutorials.

Reference: Android Switch