Tutorials Android Android Radio Button Example

Android Radio Button Example

In this tutorial, we show you how to use radio button in android  using example.

RadioButton is a  two-states button that can be either checked or unchecked. When the radio button is unchecked, the user can click it to check it. Radio button generally works with RadioGroup. Radio group can hold multiple RadioButtons, however only one can be selected at any point of time. Once a radio button is checked by user it cannot be unchecked again by pressing the same button. It automatically gets unchecked, where any other button on the same RadioGroup is selected.

Let us understand some of the RadioButton attributes and properties

  1. The android:orientation property on the Radio group defines the orientation to position its child view. It can be either horizontal  or vertical.
  2. check(id) – Sets the selection to the radio button whose identifier is passed in parameter. Using -1 as the selection identifier clears the selection.
  3. clearCheck()– Clears the selection. When the selection is cleared, no radio button in this group is selected and getCheckedRadioButtonId() returns null.
  4. getCheckedRadioButtonId() – Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
  5. setOnCheckedChangeListener() – Register a callback to be invoked when the checked radio button changes in this group. You must supply instance of RadioGroup.OnCheckedChangeListener to setOnCheckedChangeListener() method.

Android RadioButton Example

Create a new layout file named activity_main.xml under layout resource folder and add the following code snippets. The code will generate the layout as shown in the screenshot below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="How do you like the quality of our tutorials?"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <RadioGroup
        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="Excellent " />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Satisfactory" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Below Average" />
    </RadioGroup>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/clearBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClear"
            android:text="Clear " />

        <Button
            android:id="@+id/submitBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onSubmit"
            android:text="Submit" />
    </LinearLayout>
</LinearLayout>

Using RadioButton from Activity

Let us create a new java class named RadioButtonSampleActivity.java and add the following screenshot.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
    private RadioGroup radioGroup;

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

        /* Initialize Radio Group and attach click handler */
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.clearCheck();

        /* Attach CheckedChangeListener to radio group */
        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();
    }
}

Output

Android RadioButton Example

 

Total
0
Shares
guest
8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Murali Monohar
Murali Monohar
10 years ago

Simple and good example. But, how to customize the dialog similar to EULA

bob
bob
9 years ago

It seems easier to me to put an android:onClick=”radioButtonOnClick” entry in the XML for each radio button, then create a Java method public void radioButtonOnClick (View v) in the Activity code. You can use the View v parameter (cast to a RadioButton) to get hold of the particular button that was clicked.

Is there any reason why this is not a good idea?

javatechig
javatechig
9 years ago
Reply to  bob

check out my another post on android event handling.

http://stacktips.com/android/different-way-to-handle-events-in-android/

hope this will help you answer your doubt.

javatechig
javatechig
9 years ago

I strongly agree with your point. However, keeping the handler in code will help for pragmatically created UI. So in order to maintain consistency it is a good practice to have things in code rather keeping in xml.

Guest
Guest
7 years ago

When you hit the clear button, then also it displays the last selected radio button value, by code it shouldn’t display anything

Niharika88
Niharika88
5 years ago

how to store the selected value in the database

kunal
kunal
5 years ago
Reply to  Niharika88

Toast.makeText(MainActivity.this, Toast.LENGTH_SHORT).show();

Solution = String selectedvalue = rb.getText(),toString ;

Michel Gilliéron
Michel Gilliéron
4 years ago
Reply to  Niharika88

Code sample to get the value of selected radio button in a radio group:

RadioGroup radioGroup = findViewById(R.id.radioGroup);
RadioButton radioButton = findViewById(radioGroup.getCheckedRadioButtonId());
if (radioButton != null) { // Can be null if no selection !
Toast.makeText(MainActivity.this, radioButton.getText(), Toast.LENGTH_SHORT).show();
}

Previous Post
Android Tutorials

Android Menu Example

Next Post
j2me_tutorials_javatechig_featured_image

J2ME Architecture and other key concepts

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
8
0
Would love your thoughts, please comment.x
()
x