Skip to content
Related Articles

Related Articles

Dynamic Switch in Kotlin

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Jan, 2022
View Discussion
Improve Article
Save Article

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.

 

LinearLayout in activity_main.xml file

In this file, we use the LinearLayout and can not add the switch widget manually because it will be created dynamically in Kotlin file. 
 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/rootContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
 
</LinearLayout>

Add application name in strings.xml file 
Here, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen at the top of the activity. 
 

XML




<resources>
    <string name="app_name">DynamicSwitchInKotlin</string>
</resources>

Creating switches programmatically in MainActivity.kt file

Here, we initialize and define two switches and add dynamically by calling on the linearLayout. 
 

linearLayout?.addView(switch1)
linearLayout?.addView(switch2)

then, set OnClickListener on both the switches for functioning like toggle of button and Toast message like this. 
 

switch1.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg = if (isChecked) "SW1:ON" else "SW1:OFF"
            Toast.makeText(this@MainActivity, msg,
                Toast.LENGTH_SHORT).show()
        }

Complete code for the Kotlin file is below. 
 

Kotlin




package com.geeksforgeeks.myfirstkotlinapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Switch
import android.widget.Toast
 
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Creating switch1 and switch2 programmatically
        val switch1 = Switch(this)
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.
            LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        switch1.layoutParams = layoutParams
        switch1.text = "Switch1"
 
 
        val switch2 = Switch(this)
        val layoutParams2 = LinearLayout.LayoutParams(ViewGroup.
            LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        switch2.layoutParams = layoutParams2
        switch2.text = "Switch2"
 
        val linearLayout = findViewById<LinearLayout>(R.id.rootContainer)
        // Adding Switches to LinearLayout
        linearLayout?.addView(switch1)
        linearLayout?.addView(switch2)
 
        switch1.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg = if (isChecked) "SW1:ON" else "SW1:OFF"
            Toast.makeText(this@MainActivity, msg,
                Toast.LENGTH_SHORT).show()
        }
 
        switch2.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg = if (isChecked) "SW2:ON" else "SW2:OFF"
            Toast.makeText(this@MainActivity, msg,
                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:

 
 

 
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!