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 File, then New and then New Project and give name whatever you like
  • Then, select Kotlin language Support and click next button.
  • Select minimum SDK, whatever you need
  • Select Empty activity and then click finish.

After that, we need to design our layout. For that we need to work with the XML file. Go to app > res > layout and paste the folllowing code:

Modify activity_main.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:gravity="center"
        android:id="@+id/layout"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
  
</RelativeLayout>

chevron_right


MainActivity.kt

The next step is to code our RadioGroup. Open app/src/main/java/yourPackageName/MainActivity.kt and paste the following code:

filter_none

edit
close

play_arrow

link
brightness_4
code

package com.geeksforgeeks.myfirstKotlinapp
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RelativeLayout
import android.widget.Toast
   
class MainActivity : AppCompatActivity() {
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
   
        val layout = findViewById<RelativeLayout>(R.id.layout)
   
        // Create RadioButton Dynamically
        val geek1 = RadioButton(this)
        //setting height and width
        geek1.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        geek1.setText(R.string.java) //setting text of first radio button
        geek1.id = 0
   
        val geek2 = RadioButton(this)
        geek2.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        geek2.setText(R.string.python) ////setting text of second radio button
        geek2.id = 1
   
        // Create RadioGroup Dynamically
        val radioGroup = RadioGroup(this)
        val params = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.setMargins(40, 0, 0, 0)
        radioGroup.layoutParams = params
   
        //adding button to the radio group container
        radioGroup.addView(geek1)
        radioGroup.addView(geek2)
        layout.addView(radioGroup)
   
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            var text = getString(R.string.Chose)
            text += " " + getString(if (checkedId == 0) {
                R.string.java
            } else {
                R.string.python
            })
            Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
        }
   
    }
}

chevron_right


The above code will still produce some errors because we have used some strings which have been declared in another file, 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">My Application</string>
    <string name="java">Java</string>
    <string name="python">Python</string>
    <string name="Chose">You selected:</string>
  
</resources>

chevron_right


AndroidManifest.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.dynamicradiogroup"
xmlns:android="<a class="vglnk" href="http://schemas.android.com/apk/res/android" rel="nofollow">
   
    <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:






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 :

1


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