Dynamic Switch in Kotlin

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.

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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()
        }
    }
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Run as emulator for Output:

 




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.