Home » Android » core » ui » RadioButton » Android Radio Buttons Example

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Android Radio Buttons Example

One of the easiest and most common ways to accept user input in an Android Application is the Radio Button component. Usually, we want radio buttons to be in groups, representing a set of options. In a group, when a radio button is selected all the other options in this group are automatically deselected. But you can also choose to have interdependent radio buttons in your application, in which case the previous rule doesn’t apply.

In this tutorial we are going to see how to set up and display radio buttons with some options for the user as well as how to put them in a group. Furthermore, we are going to use a button that when it’s pressed, a message will be displayed reflecting the selected option of the user.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created.Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">RadioButtonExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="male_ch">Male</string>
    <string name="female_ch">Female</string>
    <string name="button_label">Display</string>

</resources>

So we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Creating a RadioButton Group

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radioGenderGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio_male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/male_ch"/>

        <RadioButton
            android:id="@+id/radio_female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/female_ch"
            android:checked="true"  />

    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />

</LinearLayout>

As you can see we use the RadioGroup tag in order to create a group of options, and we place the radio buttons we want inside that group. In the code of the second radio button (the “Female” option) , notice the android:checked="true" attribute. You may use this when you want an option to be selected by default. Now you may open the Graphical layout editor to preview the User Interface you created:

4. Adding a ClickListener to the Button

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

package com.javacodegeeks.android.radiobuttonexample;

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

public class MainActivity extends Activity {

  private RadioGroup radioGroupId;
  private RadioButton radioGenderButton;
  private Button button;

  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	addButtonListener();

  }

  public void addButtonListener() {

	radioGroupId = (RadioGroup) findViewById(R.id.radioGenderGroup);

	button = (Button) findViewById(R.id.button);

	button.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {

		    // get the selected radio button from the group
			int selectedOption = radioGroupId.getCheckedRadioButtonId();

			// find the radiobutton by the previously returned id
		    radioGenderButton = (RadioButton) findViewById(selectedOption);

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

		}

	});

  }
}

5. Run the application

This is the main screen of our Application. You can see that the option “Female” is checked by default:

Now, let’s check the “Male” option an click Display:

Download Eclipse Project

This was an Android RadioButton Example. Download the Eclipse Project of this tutorial: AndroidRadioButtonExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close