Radio buttons let the user select one option from a set of mutually exclusive options. Use radio buttons if the user needs to see all available options listed. If it's not necessary to show all options, use a spinner instead.
To create each radio button option, create a
RadioButton
in your layout. Because radio buttons are mutually exclusive, group them inside
a
RadioGroup
.
The system ensures that only one radio button within a group can be selected at
a time.
Respond to click events
When the user selects a radio button, the corresponding
RadioButton
object receives an on-click event.
The following example shows a reaction to the user tapping a
RadioButton
object in a group:
<?xml version="1.0" encoding="utf-8"?> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/radio_pirates" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pirates"/> <RadioButton android:id="@+id/radio_ninjas" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ninjas"/> </RadioGroup>
Within the Activity
or Fragment
that hosts this
layout, find your radio buttons and set a change listener for each of them, as
follows:
Kotlin
findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Pirates is checked: $isChecked") } findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Ninjas is checked: $isChecked") }
Java
findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Pirates is checked: $isChecked"); } findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked -> Log.d("RADIO", "Ninjas is checked: $isChecked"); }
In this example, when the user taps one of the radio buttons, a message prints in Logcat.