VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/dynamic-radiobutton-in-kotlin/

⇱ Dynamic RadioButton in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dynamic RadioButton in Kotlin

Last Updated : 12 Jul, 2025

An Android RadioButton is a bi-state button that can be either checked or unchecked. It functions similarly to a CheckBox, but with one key difference: once selected, a RadioButton cannot be unchecked by tapping it again. RadioButtons are typically used within a RadioGroup to allow users to select only one option from multiple choices. By default, a RadioButton is in the OFF (unchecked) state, but you can change its default state using the android:checked attribute in XML. This makes RadioButtons ideal for scenarios where a single selection is required, such as choosing a payment method, selecting a gender, or picking a preferred option in a form.

You can create an RadioButton in Android using two approaches:

  1. XML Layout: Define it in the activity's XML file.
  2. Programmatically: Create and configure it in the Kotlin file.

In this article, we will create an RadioButton programmatically using Kotlin.

Step by Step Implementation

Step 1: Create a new project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with activity_main.xml file

First of all define the RadioGroup in the Linearlayout and access into the Kotlin file.

activity_main.xml:

Layout Design:

👁 Layout


Step 3: Working with MainActivity.kt file

Here, we define three radio buttons for the color and set their attributes.

val radioButton1 = RadioButton(this)
radioButton1.layoutParams= layoutParams
radioButton1.text = "Black"
radioButton1.id = 1

then, use them into RadioGroup using code:

val radioGroup: RadioGroup = findViewById(R.id.radioGroup)
radioGroup.addView(radioButton1)
radioGroup.addView(radioButton2)
radioGroup.addView(radioButton3)

MainActivity.kt:

Output:

Comment
Article Tags:

Explore