Skip to content
Related Articles

Related Articles

Switch in Kotlin
  • Last Updated : 13 Oct, 2019

Android Switch is also two-state user interface element which is used to toggle between ON and OFF as a button. By touching the button we can drag 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 Switch object. By default, 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 in using Switch in XML layout file or create 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 AttributesDescription
android:idUsed to uniquely identify the control.
android:gravityUsed to specify how to align the text like left, right, center, top, etc.
android:checkedUsed to specify the current state of switch control.
android:thumbUsed to set drawable to be used as thumb that can be moved back and forth.
android:thumbTintUsed to set tint to apply to the thumb.
android:textUsed to set the text of the Switch.
android:textOnUsed to set the text when toggle button is in ON (Checked) state.
android:textOffUsed to set the text when toggle button is in Off (unchecked) state.
android:textStyleUsed to set style of the text. For example, bold, italic, bolditalic etc.
android:textColorUsed to set color of the text.
android:textSizeUsed to set size of the text.
android:backgroundUsed to set background color of the toggle button.
android:drawableBottomUsed to set drawable to the bottom of the text.
android:drawableLeftUsed to set drawable to left of the text.
android:drawableRightUsed to set drawable to the right of text.
android:paddingUsed 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 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.




<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.




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 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 shown in the emulator when we run the above code. We can change the state of the switches independently.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :