Open In App

Switch in Kotlin

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

  1. Click on File, then New => New Project.
  2. After that include the Kotlin support and click on next.
  3. Select the minimum SDK as per convenience and click next button.
  4. Then select the Empty activity => next => finish.

 

Different attributes of Switch widget

 

XML Attributes Description
android:id Used to uniquely identify the control.
android:gravity Used to specify how to align the text like left, right, center, top, etc.
android:checked Used to specify the current state of switch control.
android:thumb Used to set drawable to be used as thumb that can be moved back and forth.
android:thumbTint Used to set tint to apply to the thumb.
android:text Used to set the text of the Switch.
android:textOn Used to set the text when toggle button is in ON (Checked) state.
android:textOff Used to set the text when toggle button is in Off (unchecked) state.
android:textStyle Used to set style of the text. For example, bold, italic, bolditalic etc.
android:textColor Used to set color of the text.
android:textSize Used to set size of the text.
android:background Used to set background color of the toggle button.
android:drawableBottom Used to set drawable to the bottom of the text.
android:drawableLeft Used to set drawable to left of the text.
android:drawableRight Used to set drawable to the right of text.
android:padding Used to set the padding from left, right, top and bottom.

 

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. 
 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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>


Accessing the Switch widget in MainActivity.kt file

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.myfirstkotlinapp
import android.os.Bundle
import android.widget.Switch
import android.widget.Toast
import 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()
        })
    }
}


AndroidManifest.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
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>


Run as emulator for output:

Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently. 
 

 

 

 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads