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.
The above code will still produce some errors, to resolve these add the following code snippet to app/res/values/strings.xml
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)
Run as Emulator for output:
Please Login to comment...