android kotlin - Get RadioGroup selected item

Introduction

This code demonstrates how to retrieve the text associated with the selected item in a RadioGroup within an Android application written in Kotlin. The RadioGroup allows users to choose only one option from a set of radio buttons. The code utilizes a button click event to trigger the retrieval and display of the selected radio button's text.

Breakdown of the Code

MainActivity.kt:

  1. Imports: Necessary libraries are imported, including android.os.Bundle, android.widget.RadioButton, androidx.appcompat.app.AppCompatActivity, and kotlinx.android.synthetic.main.activity_main.
  2. Class Definition: The MainActivity class inherits from AppCompatActivity, which is the base class for most activities in Android.
  3. onCreate Method: This method is called when the activity is first created.
    • Sets the layout of the activity using setContentView(R.layout.activity_main).
    • Attaches a click listener to the button with button.setOnClickListener.
      • Inside the listener:
        • Retrieves the ID of the checked radio button using radioGroup.checkedRadioButtonId.
        • Uses a when statement to handle different scenarios:
          • If the ID is -1 (indicating no selection), displays "Nothing selected" in textView2.
          • Otherwise, finds the RadioButton with the retrieved ID using findViewById<RadioButton>(id).
          • Sets the text of textView2 to the text of the selected RadioButton.

activity_main.xml:

  1. Root Layout: Defines the root ConstraintLayout for the activity UI.
  2. Question Text: A TextView displays the question "Which is your most favorite?".
  3. RadioGroup: Defines a RadioGroup with four child radio buttons representing different options like "Flash", "Flex", etc.
  4. Selected Item Text: A TextView displays the text of the selected radio button (initially set to "TextView").
  5. Get Checked Item Button: A MaterialButton triggers the retrieval of selected item text when clicked.

Summary

This code showcases a practical approach to programmatically determine the selected radio button in an Android application using Kotlin. The button click event triggers the code to identify the chosen option and display its corresponding text in a designated TextView. This demonstrates a user interaction scenario where feedback is provided based on the user's selection within the RadioGroup.


MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.widget.RadioButton
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        button.setOnClickListener {
            // get radio group checked / selected item id
            val id  = radioGroup.checkedRadioButtonId
            when(id){
                -1->{ // return -1 when none selected
                    textView2.text = "Nothing selected."
                }else->{
                    val selectedItem = findViewById<RadioButton>(id)
                    // show the checked / selected item text in text view
                    textView2.text = selectedItem.text
                }
            }
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#F5F5F5">

    <TextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Headline6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:padding="8dp"
        android:text="Which is your most favorite?"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="2dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioFlash"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Flash" />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioFlex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Flex" />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioColdFusion"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ColdFusion" />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/radioPhotoshop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Photoshop" />

    </RadioGroup>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/TextAppearance.MaterialComponents.Headline5"
        android:textStyle="bold"
        android:layout_marginTop="16dp"
        android:textColor="#483D8B"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.547"
        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Get Checked Item Text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials