Signup/Sign In

Using Radio Button and Check Box in Android

By now you must be very much familiar with EditText and TextView and various layouts. Let's move on and learn more about other views like RadioButton and CheckBox.

In this tutorial we are going to design a form where user will have to select one of the options using radio button. There will be some more suggestions and options that the user will have to select using check boxes. Then we will display all the options selected by the user using a Toast on the display screen.


Let's start with RadioButton and RadioGroup

So let's begin. Create a new Android Application Project and copy the below content of the XML layout file.

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

    <TextView
        android:id="@+id/tvRg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="Rate This Lesson"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvRg"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal"
        android:showDividers="beginning|middle|end"
        android:layout_marginTop="10dp"
        android:id="@+id/radioGroup" >


        <RadioButton
            android:id="@+id/rb1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EXCELLENT"
            android:checked="false" />

        <RadioButton
            android:id="@+id/rb2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GOOD"
            android:checked="true" />

        <RadioButton
            android:id="@+id/rb3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OKAY"
            android:checked="false" />

        <RadioButton
            android:id="@+id/rb4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="POOR"
            android:checked="false" />

    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SUBMIT"
        android:id="@+id/btnSubmit"
        android:layout_below="@+id/radioGroup"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"/>
        
</RelativeLayout>

You will see the following output:


Using RadioButton and CheckBox in Android

Once the layout is done, we will now work on the background logic(backend) of the user interface which will fetch the user selection and display it on the screen using a toast.

So we will require the views that the user will interact with so that we can get the necessary information. Then we need to implement click listener on the Submit button.

Inside the onClickListener() first we have to get the selected radio button id from the RadioGroup. Once we have the id of the selected Radio Button, we can easily fetch the text value of the selected radio button to display it on screen. Let's implement this. Below we have the MainActivity.java file with all the code.

package com.example.akshay.studytonightandroid;

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

public class MainActivity extends AppCompatActivity {

    // These are the global variables
    RadioGroup radioGroup;
    RadioButton selectedRadioButton;
    Button buttonSubmit;

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

        // layout instances
        buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);

        /*
            Submit Button
        */
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // get the selected RadioButton of the group
                selectedRadioButton  = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
                //get RadioButton text
                String yourVote = selectedRadioButton.getText().toString();
                // display it as Toast to the user
                Toast.makeText(MainActivity.this, "Selected Radio Button is:" + yourVote , Toast.LENGTH_LONG).show();
            }
        });
    }
}

To get the selected radio button, we have used radioGroup.getCheckedRadioButtonId() method, which returns the id of the selected radio button.

Then to get the text of the selected radio button, we have used getText() method on that selected radio button. The text we receive from this method is converted to String type using the toString() method. Finally, we have displayed the selected option value to the user using a Toast.

Add the above code in the MainActivity.java file and then run your Android Application Project. The result will be similar to the image shown below. Whenever the user selects any option, it will be displayed to the user as a Toast.

RadioGroup, RadioButton and CheckBox in Android


It's Time for CheckBox

Now, it's time to play with some check boxes. Extend the UI design by copy-pasting the following code after the Button view (with id as btnSubmit) in the layout XML file.

<TextView
    android:id="@+id/tvCb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/radioGroup"
    android:gravity="center"
    android:text="Give Your Suggestions Here."
    android:layout_marginTop="65dp"
    android:textAppearance="?android:attr/textAppearanceMedium"/>

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text=" I really enjoy this lesson."
    android:id="@+id/cb1"
    android:layout_below="@+id/tvCb"
    android:layout_centerHorizontal="true"
    android:checked="false"/>

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="I will prefer this lesson over any other."
    android:id="@+id/cb2"
    android:layout_below="@+id/cb1"
    android:layout_centerHorizontal="true"
    android:checked="false"/>

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="I would like to hear more from you."
    android:id="@+id/cb3"
    android:layout_below="@+id/cb2"
    android:layout_centerHorizontal="true"
    android:checked="false"/>

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="I am satisfied with the content and full description."
    android:id="@+id/cb4"
    android:layout_below="@+id/cb3"
    android:layout_centerHorizontal="true"
    android:checked="false"/>

IMPORTANT: For the SUBMIT button we must set this property: android:layout_below="@+id/cb4", to make it appear at the end, as we have added checkboxes to our existing form now.

Checkboxes are used to display multiple options to the user, and the user is allowed to select one or more out of those options. All check boxes have the checked property set to false initially.

To get user selected check box values from the UI when the user clicks on the SUBMIT button, we will use the isChecked() to check if the check box was selected or not.

So we will have to make a few changes in our MainActivity.java class file. First we will have to create instances for the check boxes by using findViewById() method. For this, we also have to declare global variables of CheckBox type.

To declare the global variable,

CheckBox cb1, cb2, cb3, cb4;

Then, inside the onCreate() method, store the CheckBox view from the XML into Java using findViewById() method.

cb1 = (CheckBox) findViewById(R.id.cb1);
cb2 = (CheckBox) findViewById(R.id.cb2);
cb3 = (CheckBox) findViewById(R.id.cb3);
cb4 = (CheckBox) findViewById(R.id.cb4);

Once we have all the instances ready, all we have to do is check which checkboxes are selected by the user when the user clicks on the SUBMIT button. This is done by using isChecked() method of the CheckBox view, as we already mentioned.

isChecked() method returns true if a checkbox is checked otherwise it returns false. Selected checkboxes values are retrieved and added to one string(checkBoxChoices) using getText() and toString() methods. At last, a Toast is used to display all the selected options.

So update the existing code inside the OnClick() method of the SUBMIT button with the following code:

/*
    Submit Button
*/
buttonSubmit.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        //Get the selected RadioButton
        selectedRadioButton  = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
        // get RadioButton text
        String yourVote = selectedRadioButton.getText().toString();
    
        String checkBoxChoices = "";
    
        if (cb1.isChecked()) {
            checkBoxChoices += cb1.getText().toString() + "\tYES";
        }
        else{
            checkBoxChoices += cb1.getText().toString() + "\tNO";
        }
        
        if (cb2.isChecked()) {
            checkBoxChoices += cb2.getText().toString() + "\tYES";
        }
        else{
            checkBoxChoices += cb2.getText().toString() + "\tNO";
        }
        
        if (cb3.isChecked()) {
            checkBoxChoices += cb3.getText().toString() + "\tYES";
        }
        else{
            checkBoxChoices += cb3.getText().toString() + "\tNO";
        }
        
        if (cb4.isChecked()) {
            checkBoxChoices += cb4.getText().toString() + "\tYES";
        }
        else{
            checkBoxChoices += cb4.getText().toString() + "\tNO";
        }
    
        // display it as Toast to the user
    
        Toast.makeText(MainActivity.this, "Selected Radio Button is:" + yourVote + "\n CheckBox Choices: \n "+ checkBoxChoices , Toast.LENGTH_LONG).show();
        
    }
});

Using RadioGroup, RadioButton and CheckBox in Android    RadioGroup, RadioButton and CheckBox in Android


When you run the app, you will see that out all the radio buttons, you are able to select only one radio button while in case of check boxes, you can select any number of them. That is how radio buttons and checkboxes work. So this is all about implementation of RadioButton and CheckBox in Android Application Development.