Android ToggleButton using Kotlin With Examples

In this tutorial, we’ll learn how to implement Android ToggleButton using Kotlin. We will learn how to create custom toggle buttons and how do they work.

What is Android ToggleButton?

Android ToggleButton widget is used to toggle the state of the Button(checked/unchecked).

Difference between ToggleButton and RadioButton

A RadioButton cannot change the state once it’s clicked unless it’s present in a RadioGroup.

A ToggleButton is closer to a Switch Widget that is available with Material Design.

Difference between ToggleButton and Switch

The Switch Widget has a slider control while the ToggleButton does not have it.

ToggleButton Attributes

ToggleButton extends the Button class. It inherits most of the Button attributes such as android:text, android:drawableRight, android:textAllCaps, and android:background.

Some of the important ToggleButton attributes are:

  • android:textOn
  • android:textOff
  • android:disableAlpha
  • android:checked

Defining a Toggle Button in XML

By default Toggle button:

  • checked attribute is false
  • textOff attribute is OFF
  • textOn attribute is ON
  • The indicator color is colorAccent that’s defined in the styles.xml file.

Creating ToggleButton Programmatically using Kotlin

The textOn, textOff, and isChecked properties behave as getter and setter methods.

Setting a Listener on the ToggleButton

We have to implement CompoundButton.OnCheckedChangeListener interface callback method to invoke it when the ToggleButton is selected.

There are following listener methods for ToggleButton.

Android ToggleButton Kotlin Example Project

We’ve created two drawables using Vector Assets in our drawable directory. The toggle_drawable.xml acts as the background selector. It will set the appropriate background according to the state of the toggle button.

ToggleButton Kotlin Code

The code for the background selector toggle_drawable.xml is given below.

It’ll show the relevant image on the ToggleButton based on the state – checked/unchecked.

The code for the activity_main.xml layout file is given below.

We have to set empty field explicitly in textOn and textOff otherwise they’ll show default values.

The code for the MainActivity.kt class is given below.

We are implementing CompundButton.OnCheckedChangeListener interface. We are overriding the onCheckChanged function in our Kotlin class.

Thanks to android kotlin extensions, we don’t have to use findViewById to get the xml widgets in our Activity class.

Inside the onCheckChanged function, we’ve used “when statement” to display a Toast message showing whether the Button was checked/unchecked.

Kotlin Functions allow us to set default values for the parameters.

Custom ToggleButton

We can set styles on our ToggleButton inside the styles.xml file.

To set the custom style on our ToggleButton:

Custom Toggle Button Output:

android custom toggle button output

By admin

Leave a Reply

%d bloggers like this: