Radio buttons allow the user to select one option from a set. You use radio buttons when you want the user to choose from a set of options. The user just need to click on the radio button of his/her choice.
To create a radio button, you add the RadioButton in your layout. You also need the RadioGroup in your layout to group your radio buttons and make it exclusive and so that only one radio button can be selected at a time.
Below are the steps in creating the RadioButton example.
Step 1:
Create an Android project named HelloRadioButton. The project structure will look like this.
Step 2:
Under /res/values folder, update the strings.xml so that it will have the following values:
Step 3:
Update the layout file so that it will display the RadioButton widgets. Take note that we enclose the RadioButton with the RadioGroup so that it will become exclusive.
Step 4:
Next, we need to update our source code. We will be creating the method addListenerOnButton() so that it will add a click listener on the button and display some message when clicked.
Make sure to import the following classes:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
Step 5:
Run the HelloRadioButton program. The output will look like this: