Open In App
Related Articles

Dynamic ToggleButton in Kotlin

Improve Article
Save Article
Like Article

In Android, ToggleButton is just like a switch containing two states either ON or OFF which is represented using boolean values true and false respectively. ToggleButton unlike switch does not have a slider interface i.e we cannot slide to change the states. It is just like a button. In this article, we will be discussing how to create a ToggleButton in Kotlin dynamically.

Note: ToggleButton inherits the button class of android. Therefore, all the attributes of the button are also applicable here.

Following are some of the additional important attributes available along ToggleButton

android:disabledAlphaIt is used to adjust the alpha value of the button when it is disabled
android:textOnThe text which is shown when button is on or checked
android:textOffThe text which is shown when button is off or unchecked

Create a new project in Android Studio

To create a new project in Android Studio follow these steps:

  1. Click on File, then New and then New Project and give name whatever you like.
  2. Choose “Empty Activity” for the project template.
  3. Then, select Kotlin language Support and click next button.
  4. Select minimum SDK, whatever you need

This is how your project directory should look like:

Modify activity_main.xml file


<?xml version="1.0" encoding="utf-8"?>

Create ToogleButton in MainActivity.kt file

Insert following code in your MainActivity.kt.


package gfg.apps.togglebutton
import android.os.Bundle
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import android.widget.ToggleButton
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // accessing the layout
        val linearLayout = findViewById<LinearLayout>(
        // Create ToggleButton Dynamically
        val toggleButton = ToggleButton(this)
        toggleButton.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        // checking the state of button and printing toast accordingly
        toggleButton.setOnCheckedChangeListener { buttonView, isChecked ->
            val msg = "GFG SALE is " + if (isChecked) "ON" else "OFF"
            Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
        // Add ToggleButton to LinearLayout

AndroidManifest.xml file


<?xml version="1.0" encoding="utf-8"?>
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Run on Emulator

Last Updated : 03 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials