Android | How to add Radio Buttons in an Android Application?

Pre-requisites:

Android radio button is a widget which can have more than option to choose from and the user can choose only one option at a time. Each option in this refers to a radio button and all the options for a topic are together referred to as Radio Group. Hence, Radio buttons are used inside a RadioGroup.

For Example:

This image shows 4 options of subjects for a question. In this, each mentioned subject is a Radio Button and all the 4 subjects are together enclosed in a Radio Group.

How to create an Android App to use Radio Buttons

This example will help to develop an Android App that creates Radio Buttons according to the example shown above:

  • Step1: Firstly create a new Android Application. This will create an XML file “activity_main.xml” and a Java File “MainActivity.Java”. Please refer the pre-requisites to learn more about this step.

  • Step2: Open “activity_main.xml” file and add following widgets in a Relative Layout:
    • A TextView to display the question message
    • A RadioGroup to hold the option Radio Buttons which are the possible answers
    • 4 RadioButtons to hold an answer each.
    • A Submit and a Clear button to store the response.

    Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files.

    Syntax:

    android:id="@+id/id_name"

    Here the given IDs are as follows:

    • RadioGroup: groupradio
    • RadioButton1: radia_id1
    • RadioButton2: radia_id2
    • RadioButton3: radia_id3
    • RadioButton4: radia_id4
    • Submit Button: submit
    • Clear Button: clear

    This will make the UI of the Application.

  • Step3: Now, after the UI, this step will create the Backend of the App. For this, open the “MainActivity.java” file and instantiate the components made in the XML file (RadioGroup, TextView, Clear, and Submit Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.

    General Syntax:

    ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);

    Syntax for components used:

    Button submit = (Button)findViewById(R.id.submit);
    Button clear = (Button)findViewById(R.id.clear);
    RadioGroup radioGroup = (RadioGroup)findViewById(R.id.groupradio);

  • Step4: This step involves setting up the operations on the RadioGroup, RadioButtons and the Submit and Clear Buttons. These operations are as follows:
    1. Unset all the Radio Buttons initially as the default value. This is done by the following command:
      radioGroup.clearCheck();
    2. Add the Listener on the RadioGroup. This will help to know whenever the user clicks on any Radio Button, and the further operation will be performed. The listener can be added as follows:

      radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){}

    3. Define the operations to be done when a radio button is clicked. This involves getting the specific radio button that has been clicked, using its id. Then this radio button gets set and the rest of the radio button is reset.
    4. Add the listener on Submit button and clear button. This will be used to check when the user clicks on the button. This is done as follows:

      submit.setOnClickListener(new View.OnClickListener() {}
      clear.setOnClickListener(new View.OnClickListener() {}

    5. In the Submit Button Listener, set the operations to be performed. This involves displaying the marked answer in the form of Toast.
    6. In the Clear Button Listener, set the operations to be performed. This involves resetting all the radio buttons.
  • Step5: Now run the app and operate as follows:
    • When the app is openned, it displays a question with 4 answers and a clear and submit button.
    • When any answer is clicked, that radio button gets set.
    • Clicking on anyother radio button sets that one and resets the others.
    • Clicking on Submit button displays the currently marked answer as a Toast.
    • Clicking on Clear button resets all the radio buttons to their default state.

Complete code of MainActivity.java and activity_main.xml of RadioButton is below.

activity_main.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select your Subject ?"
        android:textStyle="bold"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"/>
  
    <!-- add RadioGroup which contain the many RadioButton-->
    <RadioGroup
        android:layout_marginTop="50dp"
        android:id="@+id/groupradio"
        android:layout_marginLeft="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
  
         <!-- In RadioGroup create the 1 Radio Button-->
         <!-- like this we will add some more Radio Button-->
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radia_id1"
            android:text="DBMS"
            android:textSize="20dp"/>
  
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radia_id2"
            android:text="C/C++ Programing"
            android:textSize="20dp"/>
  
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radia_id3"
            android:text="Data Structure"
            android:textSize="20dp"/>
  
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radia_id4"
            android:text="Algorithms"
            android:textSize="20dp"/>
    </RadioGroup>
  
    <!-- add button For Submit the Selected item-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/submit"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_marginTop="200dp"
        android:layout_marginLeft="180dp"
        />
  
    <!-- add clear button for clear the selected item-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear"
        android:id="@+id/clear"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_marginTop="200dp"
        android:layout_marginLeft="20dp"
        />
  
</RelativeLayout>

chevron_right


MainActivity.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package org.geeksforgeeks.navedmalik.radiobuttons;
  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 {
  
    // Define the object for Radio Group,
    // Submit and Clear buttons
    private RadioGroup radioGroup;
    Button submit, clear;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Bind the components to their respective objects
        // by assigning their IDs
        // with the help of findViewById() method
        submit = (Button)findViewById(R.id.submit);
        clear = (Button)findViewById(R.id.clear);
        radioGroup = (RadioGroup)findViewById(R.id.groupradio);
  
        // Uncheck or reset the radio buttons initially
        radioGroup.clearCheck();
  
        // Add the Listener to the RadioGroup
        radioGroup.setOnCheckedChangeListener(
            new RadioGroup
                .OnCheckedChangeListener() {
                    @Override
  
                    // The flow will come here when
                    // any of the radio buttons in the radioGroup
                    // has been clicked
  
                    // Check which radio button has been clicked
                    public void onCheckedChanged(RadioGroup group,
                                                 int checkedId)
                    {
  
                        // Get the selected Radio Button
                        RadioButton
                            radioButton
                            = (RadioButton)group
                                  .findViewById(checkedId);
                    }
                });
  
        // Add the Listener to the Submit Button
        submit.setOnClickListener(new View.OnClickListener() {
  
            @Override
            public void onClick(View v)
            {
  
                // When submit button is clicked,
                // Ge the Radio Button which is set
                // If no Radio Button is set, -1 will be returned
                int selectedId = radioGroup.getCheckedRadioButtonId();
                if (selectedId == -1) {
                    Toast.makeText(MainActivity.this,
                                   "No answer has been selected",
                                   Toast.LENGTH_SHORT)
                        .show();
                }
                else {
  
                    RadioButton radioButton
                        = (RadioButton)radioGroup
                              .findViewById(selectedId);
  
                    // Now display the value of selected item
                    // by the Toast message
                    Toast.makeText(MainActivity.this,
                                   radioButton.getText(),
                                   Toast.LENGTH_SHORT)
                        .show();
                }
            }
        });
  
        // Add the Listener to the Submit Button
        clear.setOnClickListener(new View.OnClickListener() {
  
            @Override
            public void onClick(View v)
            {
  
                // Clear RadioGroup
                // i.e. reset all the Radio Buttons
                radioGroup.clearCheck();
            }
        });
    }
}

chevron_right



Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.