Android Radio Button Example

Radio Button in android apps are very common. In this tutorial we’ll implement android radio button widget in our application. Radio Buttons are used when we need to select only one item from a list of presented items.

Android Radio Button

A radio button consists of two states – checked and unchecked. Clicking an unchecked button changes its state to “checked” state and “unchecked” for the previously selected radio button. To toggle a checked state to unchecked state, we need to chose another item. Clicking a checked state button doesn’t do any good. A RadioGroup is a set of radio buttons. Radio Buttons that have different parent ViewGroup can’t be termed as a RadioGroup.

Android Radio Button attributes

Some of the attributes of android radio button and radio group are listed below:

  1. android:orientation : This property on the Radio group defines the orientation to position its child view consisting of Radio Buttons. It can be either horizontal or vertical
  2. check(id) : This sets the selection to the radio button whose identifier is passed in parameter. -1 is used as the selection identifier to clear the selection
  3. clearCheck() : It clears the selection. When the selection is cleared, no radio button in this group is selected and getCheckedRadioButtonId() returns null
  4. getCheckedRadioButtonId() : It returns the identifier of the selected radio button in this group. If its empty selection, the returned value is -1
  5. setOnCheckedChangeListener() : This registers a callback to be invoked when the checked radio button changes in this group. We must supply instance of RadioGroup.OnCheckedChangeListener to setOnCheckedChangeListener() method

Radio Button Android App Example

Let’s jump onto the implementation of radio button in android application.

Android Radio Button Example Project Structure


Android Radio Button Example Code

The activity_main.xml consists of a RadioGroup containing three radio buttons and two other buttons to clear the checked states and submit the current checked state.

The source code is given below:

As it’s seen in the code, the RadioGroup check is cleared initially by invoking clearCheck() on the RadioGroup object.

A Toast is displayed whenever the checked state is changed to a new Radio Button. The toast displays the text attached to that Radio Button.

Clicking the submit button retrieves the id of the current checked RadioButton by invoking getCheckedRadioButtonId() on the radio group object.

The output of the radio button android project in action is given below:
radio button in android app

This brings an end to this tutorial. You can download the final Android Radio Button Project from the link below.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: