Dynamic RadioButton in Kotlin

19 Feb, 2021
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.
First of all define the RadioGroup in the Linearlayout and access into the Kotlin file.
<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/container"    xmlns:app="http://schemas.android.com/apk/res-auto"    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>
The above code will still produce some errors, to resolve these add the following code snippet to app/res/values/strings.xml
<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>
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)

package com.geeksforgeeks.myfirstkotlinappimport android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.LinearLayoutimport android.widget.RadioButtonimport android.widget.RadioGroupimport 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()           }        }    }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"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>
 
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android