Switch in Kotlin

27 Jan, 2022
Android Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = “true” in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps:  
Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish.
Click on File, then New => New Project.
After that include the Kotlin support and click on next.
Select the minimum SDK as per convenience and click next button.
Then select the Empty activity => next => finish.
 
 
 
In this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc.  
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:orientation="vertical">     <Switch        android:id="@+id/switch1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Switch1"/>    <Switch        android:id="@+id/switch2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Switch2"/></LinearLayout>
Add application name in strings.xml.  
XML
<resources>    <string name="app_name">SwitchInKotlin</string></resources>
Here, we will access the switches by using their respective id’s and set click Listener 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 sw1 = findViewById(R.id.switch1)
then, set OnClick listener on the switch and use if condition to check the state of the button.  
 
sw1?.setOnCheckedChangeListener({ _ , isChecked ->
            val message = if (isChecked) "Switch1:ON" else "Switch1:OFF"
            Toast.makeText(this@MainActivity, message,
                Toast.LENGTH_SHORT).show()
        })
Repeat the process for another switch in the kotlin file.  
Kotlin
package com.geeksforgeeks.myfirstkotlinappimport android.os.Bundleimport android.widget.Switchimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)         val sw1 = findViewById<Switch>(R.id.switch1)        sw1?.setOnCheckedChangeListener({ _ , isChecked ->            val message = if (isChecked) "Switch1:ON" else "Switch1:OFF"            Toast.makeText(this@MainActivity, message,                Toast.LENGTH_SHORT).show()        })         val sw2 = findViewById<Switch>(R.id.switch2)        sw2?.setOnCheckedChangeListener({ _ , isChecked ->            val message = if (isChecked) "Switch2:ON" else "Switch2:OFF"            Toast.makeText(this@MainActivity, message,                Toast.LENGTH_SHORT).show()        })    }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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>
Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently.  
 
 
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
How to Communicate Between Fragments in Android?
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Suspend Function In Kotlin Coroutines