Tuesday, February 6, 2018

android kotlin - RadioGroup and RadioButton example

Kotlin RadioGroup & RadioButton
RadioGroup and RadioButton are the widgets of the native android SDK. The RadioGroup class is used to create a single selection RadioButtons group. Checking one RadioButton from a RadioGroup unchecks any previously checked RadioButton within the same RadioGroup.

The following android application development tutorial will demonstrate how we can create and use a RadioGroup with RadioButtons. To make this tutorial code, we used the Kotlin programming language.

Initially, all of the RadioButtons are unchecked, but we can set a default checked RadioButton using ReadioGroup Tag ‘checkedButton’ attribute or corresponding method in Kotlin code. It is not possible to uncheck a particular RadioButton. But the RadioGroup can be cleared to remove the checked state. The RadioGroup class clearCheck() method unchecked all Radio buttons from the group.

RadioButtons allow the app users to select an item from the list. Developers should use RadioButtons for optional sets that are mutually exclusive that also need to display side by side. Each RadioButton in a RadioGroup represents an option. RadioButtons are mutually exclusive, so developers must group them together inside a RadioGroup. It ensures that only one RadioButton can be selected at a time.

The RadioGroup class OnCheckedChangeListener interface callback invoke when the checked radio button change in this group. Using this interface we can get the checked radio button details while it changed. We also can get the RadioGroup checked radio button programmatically, such as on a button click event. We also can set a click listener for each radio button of the radio group.

We can simply put the RadioGroup tag and the RadioButton tag to create a RadioGroup in an android application. The radio group selection is identified by the unique id of the radio button as defined in the XML layout file.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to test how we create a RadioGroup with RadioButtons in an android application.

And how we implemented RadioGroup functionality and get the checked radio button while users change the selection. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity
    private lateinit var radioGroup:RadioGroup

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the context
        context = this;

        // Get the widgets reference from XML layout
        val button = findViewById<Button>(R.id.button)
        radioGroup = findViewById(R.id.radioGroup)

        // Get radio group selection on checked change listener
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            val radio: RadioButton? = findViewById(checkedId)
            showToast("Checked change : ${radio?.text}")
        }

        // Get radio group selection
        button.setOnClickListener{
            // Get the checked radio button id from radio group
            val id: Int = radioGroup.checkedRadioButtonId
            if (id!=-1){ // If any radio button checked
                // Get the instance of radio button using id
                val radio:RadioButton = findViewById(id)
                showToast("Selected item : ${radio.text}")
            }else{
                // If no radio button checked in this radio group
                showToast("Nothing selected")
            }
        }
    }


    // Radio button on click listener
    fun radioButtonOnClick(view: View){
        // Get the clicked radio button instance
        val radio: RadioButton? = findViewById(
            radioGroup.checkedRadioButtonId
        )
        showToast("${radio?.text} Clicked")
    }


    // Show toast message
    private fun showToast(message:String){
        Toast.makeText(context,message,Toast.LENGTH_SHORT).show()
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp"
    android:background="#DCDCDD">

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#F4F0EC"
        android:padding="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Which is your favorite color?"
            android:textSize="20sp"
            android:textStyle="bold" />

        <RadioButton
            android:id="@+id/radioRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="radioButtonOnClick"
            android:text="RED" />

        <RadioButton
            android:id="@+id/radioGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="radioButtonOnClick"
            android:text="GREEN" />

        <RadioButton
            android:id="@+id/radioYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="radioButtonOnClick"
            android:text="YELLOW" />

        <RadioButton
            android:id="@+id/radioPink"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="radioButtonOnClick"
            android:text="PINK" />
    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Get Selected Color"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples