Android ToggleButton Kotlin

15-Sep-2024

Learn how to implement a ToggleButton in Android Studio Project with Kotlin to switch between two states

In Android Studio, you can create toggle buttons using the ToggleButton widget.


Here is the tutorial for Java



Here's a simple example to help you understand how to implement  toggle buttons in Android Studio
:


Step 1 :

File open res/layout/activity_main.xml file :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_margin="20dp"
android:orientation="vertical">

<!--set Checked -->
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="ToggleButton" />

<!-- set Text Name-->
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Enable"
android:textOff="Disible"
android:text="ToggleButton" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>

</RelativeLayout>


Step 2 :

File open com.microappvalley.newtestproject/MainActivity.kt file −



package com.microappvalley.newtestproject

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.widget.ToggleButton
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toggleButton1: ToggleButton = findViewById(R.id.toggleButton1)
val toggleButton2: ToggleButton = findViewById(R.id.toggleButton2)
val buttonSubmit: Button = findViewById(R.id.buttonSubmit)
toggleButton1.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
// Handle toggle button ON state
Toast.makeText(this@MainActivity, "Toggle Button ON", Toast.LENGTH_SHORT).show()
} else {
// Handle toggle button OFF state
Toast.makeText(this@MainActivity, "Toggle Button OFF", Toast.LENGTH_SHORT).show()
}
}

buttonSubmit.setOnClickListener() {
val switchData = "${toggleButton1.text} \n ${toggleButton2.text}"

Toast.makeText(this@MainActivity, switchData, Toast.LENGTH_SHORT).show()
}
}
}


Open Device Manager, run the emulator, and  then run the application. Next, check the working output and check the output  you declared in your code.


Output:



Comments