Radio Buttons & Radio groups in Android: Choosing a single option
Radio Buttons allow you to give users the choice to choose a single option from a list of options. To make android recognise that all the options belong to the same group and that you can select only one option, create a RadioButton
for each choice and enclose it with a RadioGroup
.
<RadioGroup android:id="@+id/radioGroup" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Option 1"/> <RadioButton android:id="@+id/radioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Option 2"/> </RadioGroup>
Initially, none of the options in a RadioGroup
are checked and once the user selects an option, only one RadioButton
in a group can be checked at a time.
To handle the RadioGroup
functionality in Java, you can use setOnCheckedChangeListener
to listen to any selection of the RadioButton
and then implement your functionality based on your chosen option.
A checkedID
will be returned in the method which can be used to find the RadioButton
by id. You can use the returned RadioButton
view to get its value as shown below.
// Find the RadioGroup view by id radioGroup = (RadioGroup) findViewById(R.id.radioGroup); // Set a listener to check the state of RadioButton radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // Use checkedId to find the RadioButton view RadioButton radioButton = (RadioButton) findViewById(checkedId); // Get the value of the RadioButton and set it to textView String selectedOption = radioButton.getText().toString(); textView.setText("Selected Option: ", selectedOption); } });
As soon as an option is selected, the TextView
gets updated and displays the value of the RadioButton
.