Android Radio Button Example

Filed Under: Android

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 project, radio button in android

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.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:background="@android:color/white"
    tools:context="com.journaldev.radiobuttons.MainActivity">


    <RadioGroup
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:id="@+id/radioGroup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Radio Button 1 "
            android:textSize="18sp"/>

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Radio Button 2"
            android:textSize="18sp"/>

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Radio Button 3"
            android:textSize="18sp"/>
    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLEAR"
        android:id="@+id/button"
        android:onClick="onClear"
        android:textSize="18sp"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/radioGroup"
        android:layout_alignStart="@+id/radioGroup" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SUBMIT"
        android:onClick="onSubmit"
        android:id="@+id/button2"
        android:textSize="18sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />


</RelativeLayout>

The MainActivity.java source code is given below:


package com.journaldev.radiobuttons;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.clearCheck();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                if (null != rb && checkedId > -1) {
                    Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    public void onClear(View v) {
        /* Clears all selected radio buttons to default */
        radioGroup.clearCheck();
    }

    public void onSubmit(View v) {
        RadioButton rb = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
        Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
    }

}

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

Comments

  1. Harminder Singh says:

    getting the same Error

  2. priyanka says:

    i got an error in above code
    @line of code::
    if(null!=rb && checkedId >-1)
    comparing resource type other than equality dangerous and usually wrong….

    1. Gagandeep Singh says:

      Getting the same error .

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages