A Switch is a widget introduced in Android 4.0, which is a two state toggle button. You can drag it to one side or the other with your fingers to toggle an option between two states, or you can simply tap on it to change that state of an option(ON or OFF). A Switch is a variant of the CheckBox. A Switch with ON and OFF state is as below,
The methods which are available for switch are as below,
setChecked() : Used to change the state of the Switch to On or OFF.
setTextOn() : Used to set the text that is to be displayed when the Switch is ON.
setTextOff() : Used to set the text that is to be displayed when the Switch is in OFF state.
getTextOn() : Used to get the text which is associated with the Switch in ON state.
getTextOff() : Used to get the text which is associated with the Switch in OFF state.
Note: since “switch” is a reserved word in JAVA, the widget is called as “Switch” and not as”switch”.
Creating a Switch
The below snippet tells you how to add a Switch widget into a layout file,
<Switch android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ON" />
You can register a listener ie. an instance of OnCheckedchangeListener() which handles the state change event of the Switch. The callback that is to be implemented is OnCheckedChange() that receives the Switch whose state is changed and the new state of the Switch.
Let us now create a sample project that explains you how to deal with Android Switch widget.
Step 1: Setting up android working Environment
Since Switch is introduced in android 4.0, I would be using Android 4.0 platform for developing this example. For more information on how to set up the working environment, please go through the post, Environment.
Step 2: Create an android project
Create an android project named “Switchdemo” with the launcher activity “SwitchdemoActivity”. If you are not familiar with creating android project, please go through the post Create an Android project.
Step 3: Create the required layouts
I would be using main.xml (the automatically created layout) for this example. If you want to know more about android layouts, please refer to one of our articles on Layouts. The code of the main.xml layout file is as below,
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <Switch android:id="@+id/switch1" android:text="Switch 1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="32dip" /> <Switch android:text="Switch 2(Default on)" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="32dip" android:checked="true" /> <Switch android:text="Switch 3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="32dip" android:textOff="LEFT" android:textOn="RIGHT" /> </LinearLayout> </LinearLayout>
As you see in the above code,
- Switch 1: This is the standard switch whose android:text attribute is set to “Switch 1”. It is just a simple switch which displays the text “Switch 1” and a button. The button’s default state is “OFF”. You can always change the default state which is being done for the second switch.
- Switch 2: This is the switch whose default state is set to “ON” state by using android:checked property. This switch displays the text “Switch 2”. This switch has android:layout_width property set to the value “match_parent” because of which you can see the switch’s button being aligned to the right side of the parent.
- Switch 3: This is the switch whose button displays the associated text “LEFT” when the switch is in “OFF” state and “RIGHT” when the switch is in “ON” state. This is being done using the properties android:textOff and android:textOn.
Step 4: Create the required Activities
I would be using the launcher activity SwitchdemoActivity which is being created when you create your project. The code remains unaltered. We would be altering SwitchdemoActivity.java as we move on with this tutorial. The code of your launcher activity SwitchdemoActivity.java is as below,
package my.app; import android.app.Activity; import android.os.Bundle; public class SwitchdemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Step 5: Declare your activities in AndroidManifest.xml file
Your launcher activity is declared automatically when your create your android application. If you want to know more about Manifest file, please go through the post manifest.
Your AndroidManifest.xml has the below code,
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".SwitchdemoActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 6: Run your application
Select the app->right click->Run As-> Android application.
The activity “SwitchdemoActivity” fires up as below,
As you can observe, the “Switch 1” has a button with OFF state(default), “Switch 2” with default being set to “ON” state and “Switch 3” with the associated text for the states being changed to “LEFT” and “RIGHT”.
Now change the states of all switches by simply tapping on it. The three switches with state being changed is as below,
So far you have seen how to create a simple switch in android and how to change the state and text associated with it. Now let us see how to add listeners which handles the state change event of the switch. As i said earlier, we have to register OnCheckedchangeListener() for android switches.
Change the “SwitchdemoActivity.java” code to the below code,
package my.app; import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Switch; import android.widget.Toast; public class SwitchdemoActivity extends Activity { /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Switch s = (Switch) findViewById(R.id.switch1); if (s != null) { s.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub String state="OFF"; if(isChecked){ state="ON"; } Toast.makeText(getApplicationContext(), "Switch 1 is "+state,Toast.LENGTH_LONG).show(); } }); } } }
In the above code I have implemented the logic for displaying the state of the Switch 1. Since onCheckedChanged() callback gives the state of each switch whose state has been changed through the parameter “isChecked”, we can make use of this to display the new state of the Switch. The logic is pretty simple. After getting the new state of the Switch, I am displaying it using the “Toast” message. If you are not familiar with using Toast messages, please go through the post Toast.
The Toast message displayed when “Switch 1” is pressed is as below,
The above picture is when the state of the Switch is changed from OFF to ON state. And when the Switch is changed from ON to OFF state, the Toast is displayed as below,
Creating Standalone Switch
You can create a Switch without the associated text which is just like a simple “Toggle Button”. For that you should not provide the property “android:text” in the respective Switch tag. Follow the below code to create such a Switch,
<Switch android:id="@+id/switch4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
The Standalone Switch is as below,
This is how you can create Switches in Android. Hope this tutorial helped you. Please post your comments for furthur queries.