Skip to content
Related Articles

Related Articles

Dynamic ToggleButton in Kotlin
  • Last Updated : 19 Feb, 2021

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

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

My Personal Notes arrow_drop_up
Recommended Articles
Page :