Android ToggleButton using Kotlin

Filed Under: Android

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

<ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="NIGHT"
        android:checked="true"
        android:textOn="DAY" />

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

val toggleButton = ToggleButton(this)
toggleButton.textOff = "ABC"
toggleButton.textOn = "DEF"
toggleButton.isChecked = true

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 toggle button listener methods

Android ToggleButton Kotlin Example Project

android togglebutton kotlin 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.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable = "@drawable/ic_bookmark_black"
        android:state_checked="true"/>
    <item android:drawable="@drawable/ic_bookmark_border"
        android:state_checked="false"/>
</selector>

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.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ToggleButton
        android:id="@+id/toggleButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="NIGHT"
        android:textOn="DAY" />

    <ToggleButton
        android:id="@+id/toggleButtonDrawable"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/toggle_drawable"
        android:checked="true"
        android:textOff=""
        android:textOn="" />

</LinearLayout>

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.

package net.androidy.androidlytogglebutton

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.CompoundButton
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        toggleButton1.setOnCheckedChangeListener(this)
        toggleButton2.setOnCheckedChangeListener(this)
        toggleButtonDrawable.setOnCheckedChangeListener(this)

    }

    override fun onCheckedChanged(p0: CompoundButton?, p1: Boolean) {
        when (p0?.id) {
            R.id.toggleButtonDrawable -> displayToast(message = "Toggle Button Drawable State is Filled? $p1")
            else -> displayToast(message = "Toggle Button State is checked? $p1")
        }
    }


    fun displayToast(context: Context = this, message: String, duration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(context, message, duration).show()
    }
}

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.

<style name="AppTheme.ToggleButton" parent="Base.Widget.AppCompat.Button">
        <item name="colorButtonNormal">@color/colorPrimaryDark</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="colorAccent">@android:color/holo_purple</item>
    </style>

To set the custom style on our ToggleButton:

<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.ToggleButton" />

Custom Toggle Button Output:

android custom toggle button output

You can download the Android Studio project from the following link: AndroidlyToggleButton

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages