Android RadioButton Control

Advertisements


A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio group, it automatically unchecks any previously checked radio button within the same group.

RadioGroup Attributes

Following are the important attributes related to RadioGroup control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time.

AttributeDescription
android:checkedButtonThis is the id of child radio button that should be checked by default within this radio group.

Inherited from android.view.View Class:

AttributeDescription
android:backgroundThis is a drawable to use as the background.
android:contentDescriptionThis defines text that briefly describes content of the view.
android:idThis supplies an identifier name for this view,
android:onClickThis is the name of the method in this View's context to invoke when the view is clicked.
android:visibilityThis controls the initial visibility of the view.

Example

This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioGroup.

StepDescription
1You will use Eclipse IDE to create an Android application and name it as GUIDemo9 under a package com.example.guidemo9 as explained in the Hello World Example chapter.
2Modify src/MainActivity.java file to add a click event.
2Modify the default content of res/layout/activity_main.xml file to include Android UI control.
3Define required constants in res/values/strings.xml file
4Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/com.example.guidemo9/MainActivity.java. This file can include each of the fundamental lifecycle methods.

package com.example.guidemo9;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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 radioGroupCricket;
  private RadioGroup radioGroupTutorials;
  private RadioButton radioBtn1;
  private RadioButton radioBtn2;
  private Button btnCricketer;
  private Button btnTutorialsPoint;

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

    // group1
    addListenerRadioGroup1();
    // group2
    addListenerRadioGroup2();
  }

  private void addListenerRadioGroup2() {
    radioGroupTutorials = (RadioGroup) findViewById
    (R.id.radioGroup2);
    btnTutorialsPoint = (Button) findViewById(R.id.button2);
    btnTutorialsPoint.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        // get selected radio button from radioGroupTutorials
        int selected = 
        radioGroupTutorials.getCheckedRadioButtonId();
        radioBtn2 = (RadioButton) findViewById(selected);
        Toast.makeText(MainActivity.this,
        radioBtn2.getText(), Toast.LENGTH_SHORT).show();
   }
    });		
  }


  private void addListenerRadioGroup1() {

    radioGroupCricket = (RadioGroup) findViewById
    (R.id.radioGroup1);
    btnCricketer = (Button) findViewById(R.id.button1);
    btnCricketer.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        // get selected radio button from radioGroupCricket
        int selected = radioGroupCricket.getCheckedRadioButtonId();
        radioBtn1 = (RadioButton) findViewById(selected);
        Toast.makeText(MainActivity.this,
        radioBtn1.getText(), Toast.LENGTH_SHORT).show();
     } 
   });	
  }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
   /* Inflate the menu; this adds items to the action bar if it 
     is present */
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
 }
}

Following will be the content of res/layout/activity_main.xml file:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/example_radiogroup" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="24dp" >

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

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

        <RadioButton
            android:id="@+id/radioGroupButton3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/example_radiogroup1button2" />
    </RadioGroup>

    <RadioGroup
        android:id="@+id/radioGroup2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/radioGroup1"
        android:layout_marginRight="15dp" >

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

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

        <RadioButton
            android:id="@+id/radioGroup2Button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/example_radiogroup2button2" />
    </RadioGroup>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/radioGroup1"
        android:layout_marginTop="25dp"
        android:text="@string/group_button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="14dp"
        android:text="@string/group_button2" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define these new constants:

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

    <string name="app_name">GUIDemo9</string>
    <string name="action_settings">Settings</string>
    <string name="example_radiogroup">Example showing RadioGroup</string>
    <string name="example_radiogroup1button0">Sachin</string>
    <string name="example_radiogroup1button1">Saurav</string>
    <string name="example_radiogroup1button2">Rahul</string>
    <string name="example_radiogroup2button0">MySQL Tutorial</string>
    <string name="example_radiogroup2button1">SQL Tutorial</string>
    <string name="example_radiogroup2button2">SQLite Tutorial</string>
    <string name="group_button1">cricketer</string>
    <string name="group_button2">tutorialspoint</string>    

</resources>

Following is the default content of AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.guidemo9"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.guidemo9.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Let's try to run your GUIDemo9 application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

The following screen will appear, here we have 2 RadioGroups i.e. radioGroupCricket and radioGroupTutorials. The cricketer Button is clicked after checking "Rahul" Radio Button:

Android RadioButton Control

The following screen will appear if we check one radio button that belongs to radioGroupTutorials radio group, it automatically unchecks any previously checked radio button within the same radioGroupTutorials group. The tutorialspoint Button is clicked after checking "SQL Tutorial" Radio Button:

Android RadioGroup Control

Exercise:

I will recommend to try above example with different attributes of RadioButton in Layout XML file as well at programming time to have different look and feel of the RadioButton. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple RadioButton controls in one activity.



Advertisements
Advertisements