Dynamic ToggleButton in Kotlin

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

ATTRIBUTES DESCRIPTION
android:disabledAlpha It is used to adjust the alpha value of the button when it is disabled
android:textOn The text which is shown when button is on or checked
android:textOff The 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:
android-project-directory

Modify activity_main.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create ToogleButton in MainActivity.kt file

Insert following code in your MainActivity.kt.

filter_none

edit
close

play_arrow

link
brightness_4
code

package gfg.apps.togglebutton
  
import androidx.appcompat.app.AppCompatActivity
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?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // accessing the layout
        val linearLayout = findViewById<LinearLayout>(R.id.layout)
  
        // 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
        linearLayout?.addView(toggleButton)
    }
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
    package="gfg.apps.togglebutton">
  
    <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 on Emulator




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.