A Switch is a widget used in Android applications to perform two-state operations, such as turning something on or off. It allows users to toggle settings between on and off with a simple switch. In this article, we will learn how to implement a Switch in Android. This Android article covered in both Java and Kotlin languages.
Step by Step Implementation
Step 1: Creating a new project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Adding Switch code in activity_main.xml file
In this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc.
activity_main.xml:
XML
<?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:background="@color/white"
android:orientation="vertical">
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch1"/>
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch2"/>
</LinearLayout>
Design UI:
Step 3: Accessing the Switch widget in MainActivity.kt file
Here, we will access the switches by using their respective ids and set onClickListener and Toast message if a switch is checked(ON) state.
First of all, declare a variable to get the switch using it's id.
val switch: SwitchCompat = findViewById(R.id.switch)
Note: We will be using SwitchCompat in this article. You can also choose to use SwitchMaterial.
then, set OnClick listener on the switch and use if condition to check the state of the button.
switch.setOnCheckedChangeListener({ _ , isChecked ->
val message = if (isChecked) "Switch:ON" else "Switch:OFF"
Toast.makeText(this, message,Toast.LENGTH_SHORT).show()
})Repeat the process for another switch in the MainActivity file.
MainActivity File:
Java
package org.geeksforgeeks.demo;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SwitchCompat switch1 = findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener((buttonView, isChecked) -> {
String message = isChecked ? "Switch1:ON" : "Switch1:OFF";
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
});
SwitchCompat switch2 = findViewById(R.id.switch2);
switch2.setOnCheckedChangeListener((buttonView, isChecked) -> {
String message = isChecked ? "Switch2:ON" : "Switch2:OFF";
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
});
}
}
Kotlin
package org.geeksforgeeks.demo
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val switch1: SwitchCompat = findViewById(R.id.switch1)
switch1.setOnCheckedChangeListener { _, isChecked ->
val message = if (isChecked) "Switch1:ON" else "Switch1:OFF"
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
val switch2: SwitchCompat = findViewById(R.id.switch2)
switch2.setOnCheckedChangeListener { _, isChecked ->
val message = if (isChecked) "Switch2:ON" else "Switch2:OFF"
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
}
Output:
Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently.
Similar Reads
Dynamic Switch in Android Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android.
7 min read
iOS vs Android The expression âiOS vs Androidâ adds fuel to fire, between two groups who put too much of pecuniary as well as emotional investment into their phone's operating system. But then, at the end of the day, who is the best? Here, I will try to compare two of the most in vogue operating systems for phones
4 min read
Dynamic TextSwitcher in Android Text Switcher is a widget in android that contains multiple text views and we can display one text at a time in it. In this article, we will take a look at How to implement a Dynamic Text Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article.
8 min read
Why Switch from iOS to Android? In the ever-evolving world of smartphones, the debate between iOS and Android remains a hot topic. While iOS has long been praised for its sleek design and seamless user experience, there are compelling reasons to switch from iOS to Android. This transition, often seen as daunting, can unlock a worl
8 min read
Switch in Kotlin Android Switch is a two-state user interface element that is used to toggle between ON and OFF similar to a button. By tapping the button we can drag it back and forth to make it either ON or OFF. The Switch element is useful when there are only two states required for an activity like to either cho
3 min read