Skip to main content

How to create a toggle button in Kotlin Android

How to create a toggle button in Kotlin Android.

Here's a step-by-step tutorial on how to create a toggle button in Kotlin for Android:

Step 1: Create a new project

Create a new Android project in your preferred IDE (e.g., Android Studio) and set up the basic project structure.

Step 2: Add a ToggleButton to the layout XML

Open the layout XML file for the activity where you want to add the toggle button (e.g., activity_main.xml) and add the following code to define the toggle button:

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Off"
android:textOn="On" />

Step 3: Find the ToggleButton in the activity

In the corresponding Kotlin activity file (e.g., MainActivity.kt), find the ToggleButton by its ID and assign it to a variable. Add the following code inside the onCreate method:

val toggleButton = findViewById<ToggleButton>(R.id.toggleButton)

Step 4: Set an initial state for the ToggleButton To set an initial state for the toggle button, you can use the isChecked property. Add the following code after finding the toggle button:

toggleButton.isChecked = true  // or false, depending on the initial state you want

Step 5: Add an OnClickListener to the ToggleButton To perform an action when the toggle button is clicked, add an OnClickListener to the toggle button. Add the following code after setting the initial state:

toggleButton.setOnClickListener {
if (toggleButton.isChecked) {
// Handle the toggle button being checked
} else {
// Handle the toggle button being unchecked
}
}

Step 6: Handle the toggle button states

Inside the OnClickListener, you can add code to handle the toggle button's checked and unchecked states. For example:

toggleButton.setOnClickListener {
if (toggleButton.isChecked) {
// Perform an action when the toggle button is checked
// e.g., show a message
Toast.makeText(this, "Toggle button is on", Toast.LENGTH_SHORT).show()
} else {
// Perform an action when the toggle button is unchecked
// e.g., hide a view
someView.visibility = View.INVISIBLE
}
}

That's it! You have successfully created a toggle button in Kotlin for Android. You can customize the toggle button's appearance and behavior further by modifying the layout XML and adding more code inside the OnClickListener.