The Wayback Machine - https://web.archive.org/web/20240927120501/https://www.geeksforgeeks.org/radiogroup-in-kotlin/
Open In App

RadioGroup in Kotlin

Last Updated : 19 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

RadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. The RadioGroup class is beneficial for placing a set of radio buttons inside it because this class adds multiple-exclusion scope feature to the radio buttons. This feature assures that the user will be able to check only one of the radio buttons among all which belongs to a RadioGroup class. If the user checks another radio button, the RadioGroup class unchecks the previously checked radio button. This feature is very important when the developer wants to have only one answer to be selected such as asking the gender of a user.

The class hierarchy of the RadioGroup class in Kotlin

Class Heirarchy of RadioGroup in Kotlin

XML attributes of RadioGroup widget

XML Attributes Description
android:id To uniquely identify the RadioGroup
android:background To set a background colour
android:onClick A method to perform certain action when RadioGroup is clicked
android:onClick It’s a name of the method to invoke when the radio button clicked.
android:visibility Used to control the visibility i.e., visible, invisible or gone
android:layout_width To set the width
android:layout_height To set the height
android:contentDescription To give a brief description of the view
android:checkedButton Stores id of child radio button that needs to be checked by default within this radio group
android:orientation To fix the orientation constant of the view

Example

In this example step by step demonstration of creating a RadioGroup will be covered, it consists of 5 RadioButton children which ask the user to choose a course offered by GeeksforGeeks. When the user checks one of the RadioButtons and clicks the Submit button a toast message appears which displays the selected option.

Note: Following steps are performed on Android Studio version 4.0

Create new project

  1. Click on File, then New => New Project.
  2. Choose “Empty Activity” for the project template.
  3. Select language as Kotlin.
  4. Select the minimum SDK as per your need.

Open activity_main.xml file

Below is the code for activity_main.xml file to add a RadioGroup and its 5 RadioButton children. A normal submit button is also added to accept and display the response selected by the user.




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#168BC34A"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/roboto"
        android:text="@string/Heading"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="36sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.19" />
  
    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#024CAF50"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.24000001">
  
        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/RadioButton1"
            android:textSize="24sp" />
  
        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/radioButton2"
            android:textSize="24sp" />
  
        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/radioButton3"
            android:textSize="24sp" />
  
        <RadioButton
            android:id="@+id/radioButton4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/radioButton4"
            android:textSize="24sp" />
  
        <RadioButton
            android:id="@+id/radioButton5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/radioButton5"
            android:textSize="24sp" />
    </RadioGroup>
  
    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#AB4CAF50"
        android:text="@string/submit_Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup1"
        app:layout_constraintVertical_bias="0.17000002" />
</androidx.constraintlayout.widget.ConstraintLayout>


Open MainActivity.kt file

Below is the code for MainActivity.kt file to access RadioGroup widget in kotlin file and show a proper message whenever a radio button is selected by the user.




package com.example.sampleproject
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
  
class MainActivity : AppCompatActivity() {
    var radioGroup: RadioGroup? = null
    lateinit var radioButton: RadioButton
    private lateinit var button: Button
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Display name of the Application
        title = "RadioGroup in Kotlin"
  
        // Assigning id of RadioGroup
        radioGroup = findViewById(R.id.radioGroup1)
  
        // Assigning id of Submit button
        button = findViewById(R.id.submitButton)
  
        // Actions to be performed 
        // when Submit button is clicked
        button.setOnClickListener {
  
            // Getting the checked radio button id 
            // from the radio group
            val selectedOption: Int = radioGroup!!.checkedRadioButtonId
  
            // Assigning id of the checked radio button
            radioButton = findViewById(selectedOption)
  
            // Displaying text of the checked radio button in the form of toast
            Toast.makeText(baseContext, radioButton.text, Toast.LENGTH_SHORT).show()
        }
    }
}


Modify strings.xml file

All the strings which are used in the activity, from the application name to the option of various RadioButtons are listed in this file.




<resources>
    <string name="app_name">RadioGroup in Kotlin</string>
    <string name="Heading">Choose a GfG course</string>
    <string name="RadioButton1">Amazon SDE Test Series</string>
    <string name="radioButton2">Placement 100</string>
    <string name="radioButton3">C++ STL</string>
    <string name="radioButton4">CS Core Subjects</string>
    <string name="radioButton5">DSA Self paced</string>
    <string name="submit_Button">Submit</string>
</resources>


Output

RadioGroup Activity

RadioGroup Activity


Previous Article
Next Article

Similar Reads

Dynamic RadioGroup in Kotlin
In Android RadioGroup is used to set radio buttons. If one radio button is selected within the RadioGroup, all other ones are automatically deselected. In this article, we will be discussing how to programmatically create a RadioGroup in Kotlin. Let’s start by first creating a project in Android Studio. To do so, follow these instructions: Click on
2 min read
RadioGroup in Android
RadioGroup is a widget in android which is used to handle multiple radio buttons within the android application. We can add multiple radio buttons to our RadioGroup. We have seen how to use radio buttons in android. In this article, we will take a look at How to implement Radio Group in the android application. A sample video is given below to get
3 min read
Kotlin Data Types
The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects. There are different data types in Kotlin: Integer Data typeFloating-point Data
3 min read
Hello World program in Kotlin
Hello, World! is the first basic program in any programming language. Let's write the first program in Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. // Kotlin Hello World Program fun main(args: Array<String>) { pri
2 min read
Android Shared Element Transition with Kotlin
Shared element transition is seen in most of the applications which are used when the user navigates between two screens. This type of animation is seen when a user clicks on the items present in the list and navigates to a different screen. During these transitions, the animation which is displayed is called a shared element transition. In this ar
4 min read
Kotlin | Retrieve Collection Parts
The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying the start and end indices of the sublist. The result
5 min read
Destructuring Declarations in Kotlin
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables correspond to the properties of a class that are associat
3 min read
DatePicker in Kotlin
Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePic
3 min read
Kotlin labelled continue
In this article, we will learn how to use continue in Kotlin. While working with a loop in the programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. Basically, continue is used to repeat the loop for a specific condition. It skips the following statements a
4 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. Step by Step Implementation 1. If you observe the ab
7 min read
Kotlin Exception Handling | try, catch, throw and finally
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions - Checked Exceptio
6 min read
A Complete Guide to Learn Kotlin For Android App Development
Kotlin is a statically typed, cross-platform, general-purpose programming language for JVM developed by JetBrains. This is a language with type inference and fully interoperable with Java. Kotlin is concise and expressive programming as it reduces the boilerplate code. Since Google I/O 2019, Android development has been Kotlin-first. Kotlin is seam
8 min read
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the condi
4 min read
Android - Save ArrayList to SharedPreferences with Kotlin
SharedPreferences is local storage in android which is used to store data in the form of key and value pairs within the android devices. We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin. A sample video is given b
9 min read
Create an Android App that Displays List of All Trending Kotlin git-hub Repositories
Kotlin is a popular programming language that has gained much attention in recent years. It is known for its simplicity, conciseness, and compatibility with existing Java code. GitHub is a popular platform for hosting and sharing code, including Kotlin projects. This article will discuss how to build an application that shows a list of Kotlin GitHu
12 min read
Kotlin Environment setup for Command Line
To set up a Kotlin environment for the command line, you need to do the following steps: Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin compiler: You can download the latest version of the
2 min read
Kotlin Environment setup with Intellij IDEA
Kotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully interoperable with Java code. Let's see how to setu
2 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year: Int inner class Engine { var horsepower: Int = 0
5 min read
Android - Line Graph View with Kotlin
Graphs are used in android applications to display vast amounts of data in an easily readable form. There are different types of graphs used such as BarGraph, GroupBar graph, point, and line graph to represent data. In this article, we will take a look at How to use Line Graph View in Android using Kotlin. A sample video is given below to get an id
3 min read
Working with Anonymous Function in Kotlin
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it can
3 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example + and - are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operatorRelation operatorAssignment operatorUnary operatorLogical operatorBitwise operator Arithmetic Operators - Op
3 min read
Kotlin Standard Input/Output
In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence of bytes or byte streams from input device such as Keyboard to the main memory of the system and from main memory to output device such as Monitor. In Java, we use System.out.pr
5 min read
Kotlin Expression, Statement and Block
Kotlin Expression - An expression consists of variables, operators, methods calls etc that produce a single value. Like other language, Kotlin expression is building blocks of any program that are usually created to produce new value. Sometimes, it can be used to assign a value to a variable in a program. It is to be noted that an expression can co
4 min read
Kotlin for loop
In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines. While loop - It consists of a block of code and a condition. First
2 min read
Kotlin do-while loop
Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes
2 min read
Kotlin Unlabelled break
When we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to nea
4 min read
Kotlin labelled break
While working with loops say you want to stop the execution of loop immediately if a certain condition is satisfied. In this case you can use either break or return expression to exit from the loop. In this article, we are going to learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to neare
4 min read