Android Toggle Switch Button

In various Android apps, we have seen different types of switches such as YouTube (switch to autoplay the next video), Truecaller(switch to enable dark theme, block calls, call recording switch, etc.), in Facebook settings, Gmail, WhatsApp(to enable fingerprint lock for security) and many other apps.

What is a Switch?

In Android Studio Switch is a two-state toggle switch widget that can be used to select between two options. It is mainly used to display the on and off state of an option, which looks like a simple slider control to the user. The user may drag the "thumb" back and forth to choose the selected option, or we can simply tap to toggle the state of the switch.

It is commonly used in selecting on/off Hotspot, Flashlight, WiFi, etc. It is the subclass of android.widget.CompoundButton class.

The Switch is similar to a ToggleButton in accordance to the function but both of them have some differences such as Switch has a spider to control the state of the switch and the UI of both Switch and ToogleButton is different.

Now we have enough knowledge about switch let's add a switch in our android app.

Step 1: Create a new Project

  1. Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to setup Android Studio and create your first Android project)

  2. Choose "Empty Activity" from the project template window and click on Next.

  3. Enter the App Name, Package name, save location, language(Java/Kotlin, we will use Java for this tutorial), and the minimum SDK(we are using API 19: Android 4.4 (KitKat))

  4. Next click on Finish button after filling in the above details.

  5. Now, wait for the project to finish building.

Step 2: Adding Switch to Android Activity

Now go to app -> res -> layout -> activity_main.xml and add Switch, now our activity_main.xml file will look like as shown below:

<?xml version = "1.0" encoding =  "utf-8" ?>
<RelativeLayout
    android:id = "@+id/constraintLayout"
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">
    
        <Switch
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"/>
    
</RelativeLayout>

In the above code, we have added the default toggle switch in our Android Activity.

Attributes of Switch with Example:

Let's know more about the attributes of Switch and how we can use them to customise the switch in android app.

1. id Attribute:

It is used to set a unique id for the switch by which we can identify a particular switch, it means different switches have different ids.

<Switch
    android:id = "@+id/mySwitchId"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"/>

2. checked Attribute:

This attribute is used to set the current state of the Switch. The value can either be true or false and the default value of checked attribute is false. When we set checked="true" the switch becomes checked by default and when we set it false the switch become unchecked.

<Switch
    android:checked = "true"
    android:id = "@+id/mySwitchId"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"/>

We can also change the checked state of the switch in the Java code using the setChecked(Boolean b) function, where b can either true or false as shown below:

Switch sw = (Switch) findViewById(R.id.mySwitchId);
sw.setChecked(true);
sw.setChecked(false);

android switch toggle example

3. text Attribute:

It is used to set the text for the Switch. We can set the text directly as shown below:

<Switch
    android:text = "Dark Mode"
    android:id = "@+id/mySwitchDarkMode"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"/>

Or we can also change the text dynamically in the Java code using the setText(CharcaterSwequence cs) function as shown below:

Switch swdark = ( Switch ) findViewById( R.id.mySwitchDarkMode );
swdark.setText( "Dark Mode" );

android switch toggle example

4. gravity Attribute:

It is used to set the gravity of the text in a Switch. The default value is left. There are many values of gravity such as right, left, center, center_horizontal, top, bottom, center_vertical, clip_horizontal, clip_vertical, end, fill, fill_horizontal, fill_vertical, and start. To view the effect of gravity we have to set android:layout_width = "match_parent"

<Switch
    android:gravity = "right"
    android:text = "Gravity Right"
    android:id = "@+id/mySwitchGravity"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can also change the text gravity at runtime in the Java code by using the setGravity(int gravity) function as shown below:

Switch swgravity = ( Switch ) findViewById( R.id.mySwitchGravity );
swgravity.setGravity( Gravity.RIGHT );

android switch toggle example

5. textOn and textOff Attributes:

The textOn attribute is used to set the text which we want to shown when Switch is in the checked state (means in on state) and textOff attribute is used to set the text which we want to shown Switch is in the unchecked state (means in off state) as shown below. To show the textOff and textOn text we have set showText = "true"

<Switch
    android:textOff = "Disable"
    android:textOn = "Enable"
    android:text = "System  Sound"
    android:id = "@+id/mySwitchTextOnOff"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:showText = "true"/>

We can also change the textOn and textOff values in the Java code by using the setTextOn(CharSeqence texton) and setTextOff(CharSeqence textoff) functions as shown below:

Switch swOnOff = ( Switch ) findViewById( R.id.mySwitchTextOnOff );
swOnOff.setTextOn( "Enabled" );
swOnOff.setTextOff( "Disabled" );

Output for textOff:

android switch toggle example

Output for textOn:

android switch toggle example

6. textColor Attribute:

It is used to set the text color of the switch. The color value can be any one of the form "#argb", "#rgb", "#rrggbb", or "#aarrggbb".

<Switch
    android:textColor = "#FF0000"
    android:text = "Color text Switch"
    android:id = "@+id/mySwitchTextColor"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can also do the same thing in the Java code using void setTextColor(int color) or void setTextColor(ColorStateList colors) functions as shown below:

Switch swtxtColor = ( Switch ) findViewById( R.id.mySwitchTextColor );
swtxtColor.setTextColor(Color.RED);

android switch toggle example

7. textSize Attribute:

This attribute is used to set the size of the Switch text. We can set the size in dp, in, mm, pt, px, sp in XML. In the example below we are setting the text size to 32 dp:

<Switch
    android:textSize = "32dp"
    android:text = " Text Size Switch"
    android:id = "@+id/mySwitchTextSize"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can change the text size from Java code by using the void setTextSize(float size) and void setTextSize(int unit, float size) functions:

Switch swtxtSize = ( Switch ) findViewById( R.id.mySwitchTextSize );
swtxtSize.setTextSize( 32 );

android switch toggle example

8. textStyle Attribute:

It is used to set the text style of the Switch text. The 3 text styles available in android are bold, normal and italic. The default text style is normal and if we want to use more than one text style then we can use the | (pipe) operator between different styles, for example, bold | italic.

<Switch
    android:textStyle = "bold"
    android:text = " Text Style Switch"
    android:id = "@+id/mySwitchTextStyle"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can change the text style from the Java code too by using the void setTypeface( Typeface tf) and void setTypeface( Typeface typeface, int style ) functions as shown below:

Switch swtxtStyle = ( Switch ) findViewById( R.id.mySwitchTextStyle );
swtxtStyle.setTypeface( Typeface.DEFAULT_BOLD );

android switch toggle example

9. background Attribute:

It is used to set the background of the switch. It can either be a color or drawable (image) or any custom xml file. For this tutorial we will add a simple red color background:

<Switch
    android:background = "#FF0000"
    android:text = " Switch With Background"
    android:id = "@+id/mySwitchBackground"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can also set the background from the Java code using the void setBackgroundColor( int color) function:

Switch swBackground = ( Switch ) findViewById( R.id.mySwitchBackground );
swBackground.setBackgroundColor( Color.RED);

android switch toggle background color example

10. padding Attribute:

It is used to set the padding to the Switch. We can either set the top, bottom, left, right padding at once using the padding attribute or we can add different padding for top, bottom, left, right using the paddingLeft, paddingRight, paddingTop, and paddingBottom attributes.

<Switch
    android:paddingLeft = "12dp"
    android:paddingBottom = "10dp"
    android:paddingTop = "14dp"
    android:paddingRight = "6dp"
    android:padding = "16dp"
    android:text = " Switch With Padding"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"/>

We can also add padding from the Java code too using the void setPadding( int left, int top, int right, int bottom ) function as shown below:

Switch swPadding = ( Switch ) findViewById( R.id.mySwitchPadding );
swPadding.setPadding(12,14,6,10 );

android switch toggle padding example

Different Listeners in Switch:

Now let's cover the event or click listener functions which can be used to capture the user click on the toggle switch and perform some action.

1. Using setOnClickListener(OnClickListener l) Listener:

We can use this listener when we want to check if the switch is clicked and make a decision according to the click. Inside the public void onClick(View view) function, we will check if the switch is checked or not using the boolean isChecked() function and show toast to the user according to the state of the switch as shown below:

final Switch aSwitch = (Switch) findViewById(R.id.mySwitchListener);

aSwitch.setOnClickListener(new View.OnClickListener() 
{
    @Override
	public void onClick(View view) {
		if (aSwitch.isChecked()) //checking if  switch is checked
		{
			Toast.makeText(MainActivity.this, "Switch is Turned On using click listener ", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(MainActivity.this, "Switch is Turned Off using click listener", Toast.LENGTH_SHORT).show();
		}
	}
});

Here are the output screens:

android switch toggle example android switch toggle example

2. Using setOnCheckedChangeListener(OnCheckedChangeListener l) Listener:

This listener is invoked when the state of the switch is changed means when we toggle the switch from off state to on state or vice versa. The main difference from onClickListener is that this is only invoked when the state changes, but onClickListener is invoked every time when we click on the Switch.

Inside the onCheckedChangeListener we have a onCheckedChanged(CompoundButton compoundButton, boolean b) and we can use a boolean value to check the state of the switch and perform the functions according the value of the boolean:

aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Override
	public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
		if (b) //checking if the user turned on the switch
		{
			Toast.makeText(MainActivity.this, "Switch is Turned On using on checked changed", Toast.LENGTH_SHORT).show();

		} else {
			Toast.makeText(MainActivity.this, "Switch is Turned Off using on checked changed", Toast.LENGTH_SHORT).show();
		}
	}
});

Here are the output screens:

android switch toggle example android switch toggle example

There are many other listeners which we can use according to our needs. These 2 listeners are the most basic and any project can be made with these listeners without any problem.