Dynamic RadioButton in Kotlin

Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to be unchecked once it was selected.

Generally, we use RadioButton controls to allow users to select one option from multiple options.

By default, the RadioButton in OFF(Unchecked) state but we can change the default state of RadioButton by using android:checked attribute.



In order to create a radio button, first we need to create a project. We are naming it a DynamicRadioButton

  • Click on File, then New => New Project
  • Then, check Include Kotlin Support and click next button.
  • Select minimum SDK, whatever you need.
  • Select Empty activity and then click finish.

Modify the activity_main.xml file

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
  
    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingStart="25dp">
    </RadioGroup>
</LinearLayout>

chevron_right


The above code will still produce some errors, to resolve these add the following code snippet to app/res/values/strings.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<resources>
    <string name="app_name">DynamicRadioButton</string>
    <string name="black">Black</string>
    <string name="white">White</string>
    <string name="blue">Blue</string>
    <string name="you_selected">You selected:</string>
  
</resources>

chevron_right


MainActivity.kt file

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

 val radioButton1 = RadioButton(this)

then, use them into RadioGroup using code:

radioGroup.addView(radioButton1)
radioGroup.addView(radioButton2)
radioGroup.addView(radioButton3)
filter_none

edit
close

play_arrow

link
brightness_4
code

package com.geeksforgeeks.myfirstkotlinapp
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
  
    @SuppressLint("ResourceType")
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        val linearLayout = findViewById<LinearLayout>(R.id.container)
  
        // Create RadioButton programmatically
        val radioButton1 = RadioButton(this)
        radioButton1.layoutParams= LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
            radioButton1.setText("Black")
        radioButton1.id = 1
  
        val radioButton2 = RadioButton(this)
        radioButton2.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
            radioButton2.setText("White")
        radioButton2.id = 2
  
        val radioButton3 = RadioButton(this)
        radioButton3.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
            radioButton3.setText("Blue")
        radioButton3.id = 3
  
        val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
        if (radioGroup != null)
        {
        radioGroup.addView(radioButton1)
        radioGroup.addView(radioButton2)
        radioGroup.addView(radioButton3)
  
            radioGroup.setOnCheckedChangeListener { group, checkedId ->
                var string = getString(R.string.you_selected)
                string += " " + getString(
                    if (checkedId == 1) R.string.black
                    else if(checkedId == 2 ) R.string.white
                    else R.string.blue )
            Toast.makeText(applicationContext, string, Toast.LENGTH_SHORT).show()
           }
        }
    }
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
package="com.geeksforgeeks.myfirstkotlinapp">
  
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
  
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
  
</manifest>

chevron_right


Run as Emulator for output:

 




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.