Android Switch Tutorial With Example

Hello Readers! In this post, we are going to learn about how to use android switch widget in any android application. We are also going to see different attributes of android switch that can be used to customise it.

Output

Tutorialwing Android Switch Widget Output Android Switch Widget tutorial with example

Tutorialwing Android Switch Widget Output

Getting Started

Android Switch widget can be defined as below –

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.

Attributes of Android Switch Widget

Some of the popular attributes of android switch widget are –

Sr. XML Attributes Description
1 android:showText Sets whether we want to show text(ON/OFF) or not
2 android:textOff Text to be shown when Switch is in OFF state.
3 android:textOn Text to be shown when Switch is in ON state.
4 android:textStyle Sets style of the text. For example, bold, italic etc.
5 android:thumb Sets drawable to be used as thumb that are moved back and forth
6 android:thumbTextPadding Sets amount of padding on either side of text within the switch thumb.
7 android:thumbTint Tint to apply to the thumb
8 android:thumbTintMode Blending mode used to apply the thumb tint
9 android:track Drawable of the track in which thumb slides back and forth
10 android:typeface Specifies typeface for the text. For example, normal, sans, serif, monospace etc.

Some of the popular attributes of android switch widget inherited from Compound Button are –

Sr. XML Attributes Description
1 android:button Sets drawable to button graphic
2 android:buttonTint Tint to apply to button tint
3 android:buttonTintMode Blending mode used to apply to button graphic tint

Some of the popular attributes of android Switch Widget inherited from TextView are –

Sr. XML Attributes Description
1 android:autoLink Specifies whether text such as email, url should be automatically detected and converted into links or not.
2 android:cursorVisible Specifies whether cursor should be visible or not.
3 android:drawableBottom Sets drawable to be shown below text
4 android:ems Makes the TextView be exactly this ems wide

Some of the popular attributes of android Switch widget inherited from View are –

Sr. XML Attributes Description
1 android:background Sets background of the view.
2 android:clickable Sets whether this view is clickable or not
3 android:focusable It controls whether a view can take focus or not
4 android:id Sets id of the view



Example of Android Switch Widget

At first, we will create android application. Then, we will use android switch widget in this application.

1. Creating New Project

Follow the steps below to create new application. Please ignore the steps if you have already created the application.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as Switch. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

Now, we will modify xml and java file to use switch widget in the application.

2. Modify Values folder

Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">Switch</string>
</resources>

Since other values folders have not been changed. So, we are not going to mention it here.

3. Use Switch Widget in xml file

Open res/layout/activity_main.xml file. Then, add below code into it.

<?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:gravity="center"
	android:orientation="vertical">

	<Switch
		android:id="@+id/switch1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="OFF"/>

</LinearLayout>

In activity_main.xml file, we have used Switch widget in xml file. Now, we will access this widget in java file.

4. Access Switch Widget in java file

Open src/main/java/com.tutorialwing.aswitch/MainActivity.java file. Then, add below code into it.

package com.tutorialwing.aswitch;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

		final Switch sw = findViewById(R.id.switch1);
		if (sw != null) {
			sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					String msg = isChecked ? "ON" : "OFF";
					Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
					sw.setText(msg);
				}
			});
		}
	}
}

In MainActivity.java, we have accessed switch widget. We have also set checked listener to show toast message that display the checked status of switch widget.

Since AndroidManifest.xml file is very important in any android application, we are also going to mention it here.

AndroidManifest.xml

Code inside src/main/AndroidManifest.xml file is as below –

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.aswitch"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

When we run the application, we will get output as shown above.

That’s end of tutorial on Android Switch widget.

Leave a Reply