Android RadioGroup and RadioButton Example

Android documentation:
RadioGroup is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group.

Intially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state.

The selection is identified by the unique id of the radio button as defined in the XML layout file.

Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive if you think that the user needs to see all available options side-by-side. If it’s not necessary to show all options side-by-side, use a spinner instead.

RadioGroup and RadioButton Code Example:
1. Defining the RadioGroup and RadioButton in a layout file:

<RadioGroup
    android:id="@+id/accuracy_choice"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/fine_accuracy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fine"/>
    <RadioButton
        android:id="@+id/coarse_accuracy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Coarse"/>
</RadioGroup>

2. Listening and getting the selected RadioButon in the code.

RadioGroup accuracyChoice = (RadioGroup) findViewById(R.id.accuracy_choice);
accuracyChoice.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.fine_accuracy) {
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            Toast.makeText(MainActivity.this, "Fine Accuracy Selected!", Toast.LENGTH_SHORT).show();
        } else if (checkedId == R.id.coarse_accuracy) {
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            Toast.makeText(MainActivity.this, "Coarse Accuracy Selected!", Toast.LENGTH_SHORT).show();
        }
    }
});

3. Get the selected RadioButton.

accuracyChoice.getCheckedRadioButtonId();

Search within Codexpedia

Custom Search

Search the entire web

Custom Search