Android ToggleButton Using Kotlin

Filed Under: Android

In this tutorial, we’ll be discussing ToggleButton and implement it using Kotlin in our Android Application. In the end, we’ll create a custom ToggleButton too and see how it works.

Android ToggleButton

Android ToggleButton is a widget used to toggle the state of the Button(checked/unchecked).
It’s different from a 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 available with Material Design.
It’s different from a Switch Widget.
The Switch Widget has a slider control while the ToggleButton does not.
Since a ToggleButton extends the Button class in Android, it inherits most of it’s attributes such as android:text, android:drawableRight, android:textAllCaps, android:background.

Following are the main attributes:

  • 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 Programmatically


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

textOn, textOff, isChecked are the properties that behave as getters and setters.

Setting a Listener on the ToggleButton
We need to implement CompoundButton.OnCheckedChangeListener interface’s callback method when the ToggleButton is selected.

We can implement either of the following methods:
android-toggle-button-listener-kotlin

Project Structure

android-toggle-button-project-structure-kotlin

We’ve created two drawables Using Vector Assets in our drawable directory. toggle_drawable.xml acts as the Background selector and will set the appropriate background according to the state.

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 need 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()
    }
}

Here, our class implements the interface, CompundButton.OnCheckedChangeListener, thus we need to override the onCheckChanged function in our Kotlin class.
Thanks to android kotlin extensions we no more need to use findViewById to get the xml widgets in our Activity class.
Inside the onCheckChanged function, we’ve used a when statement to display a Toast message showing whether that Button was checked/unchecked.
Kotlin Functions allow us to set default values in the parameters. Hence we’ve shortened our Toast invocation code.

Styling ToggleButton

Taking it a step further, we can also 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 this in on our ToggleButton, we do:


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

Setting this in our above xml layout gives us the following output when run on an emulator:
android-toggle-button-kotlin-output

This brings an end to this tutorial on ToggleButtons Using Kotlin. You can download the AndroidlyToggleButton project from the link below.

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