RadioButton in Kotlin - GeeksforGeeks

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.
Following steps to create new project-
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.
We can write the name of the application as RadioButtonInKotlin and write other strings which can be used.
<resources>    <string name="app_name">RadioButtonInKotlin</string>    <string name="checked">checked</string>    <string name="unchecked">unchecked</string></resources>
In android, we use radio buttons inside RadioGroup to combine set of radio buttons into single group and it will make sure that user can select only button from the group of buttons.
<?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/root_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="16dp">    <RadioGroup        android:id="@+id/radio_group"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#dbeceb"        android:padding="15dp">          <TextView            android:id="@+id/title"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="Which is your favorite color?"            android:textStyle="bold"            android:textSize="20sp"/>          <RadioButton            android:id="@+id/red"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="RED"            android:onClick="radio_button_click"/>          <RadioButton            android:id="@+id/green"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="GREEN"            android:onClick="radio_button_click"/>          <RadioButton            android:id="@+id/yellow"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="YELLOW"            android:onClick="radio_button_click"/>          <RadioButton            android:id="@+id/pink"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="PINK"            android:onClick="radio_button_click"/>    </RadioGroup>      <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Get Selected Color"/></LinearLayout>
Here, we are trying to implement a scenario where you need to select your favorite color. So, in activity_main.xml file, we have added 4 radio buttons inside a radio group. Each button represent a color. Now, only one radio button can be selected at a time. *
Now, we will access this widget in kotlin file and show a proper message whenever a radio button is selected.
package com.geeksforgeeks.myfirstkotlinapp  import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.*import kotlinx.android.synthetic.main.activity_main.*import android.widget.RadioGroup      class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Get radio group selected item using on checked change listener        radio_group.setOnCheckedChangeListener(            RadioGroup.OnCheckedChangeListener { group, checkedId ->                val radio: RadioButton = findViewById(checkedId)                Toast.makeText(applicationContext," On checked change :"+                        " ${radio.text}",                    Toast.LENGTH_SHORT).show()            })        // Get radio group selected status and text using button click event        button.setOnClickListener{            // Get the checked radio button id from radio group            var id: Int = radio_group.checkedRadioButtonId            if (id!=-1){ // If any radio button checked from radio group                // Get the instance of radio button using id                val radio:RadioButton = findViewById(id)                Toast.makeText(applicationContext,"On button click :" +                        " ${radio.text}",                    Toast.LENGTH_SHORT).show()            }else{                // If no radio button checked in this radio group                Toast.makeText(applicationContext,"On button click :" +                        " nothing selected",                    Toast.LENGTH_SHORT).show()            }        }    }    // Get the selected radio button text using radio button on click listener    fun radio_button_click(view: View){        // Get the clicked radio button instance        val radio: RadioButton = findViewById(radio_group.checkedRadioButtonId)        Toast.makeText(applicationContext,"On click : ${radio.text}",            Toast.LENGTH_SHORT).show()    }}
In MainActivity.kt file, we have accessed radio group in which I have added four radio buttons. Then, we have set a listener to display toast message whenever radio button selection changes.
Since AndroidManifest.xml file is very important in any android application, we are also going to mention it here.
<?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>
When You run the application, you will get the output as shown below
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Navigation Drawer in Android
Broadcast Receiver in Android With Example
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android