Android RadioButton in RadioGroup Example

In this tutorial we will see how to create radio button in android , Radio buttons allow user to select only one option at a time from a given set .
 

In android the RadioButtons usually are grouped under RadioGroup , In a group if you select one RadioButton then others are deselected .

In this tutorial , we will see an example of three Radiobutton  which are grouped under RadioGroup.

android radio buttonandroid radio button



Lets see an example of radio group 

Project Detail
Project Name RadiogroupDemo
Package com.pavan.radiogroupdemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

1. XML Layout


file:- activity_main.xml
< LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical"
     android:padding="20px" >

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

                 < RadioButton
                      android:id="@+id/radio_android"
                      android:text="Android" />

                 < RadioButton
                      android:id="@+id/radio_ios"
                      android:text="IOS" />

                 < RadioButton
                      android:id="@+id/radio_windows"
                      android:text="Windows" />
 
     < /RadioGroup>
 
< /LinearLayout>

2. Activity


file : MainActivity.java
package com.pavan.radiogroupdemo;
import com.pavan.androidradiogroupdemo.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnCheckedChangeListener {

 RadioGroup radiogroup;
 RadioButton radiobutton;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // get the id's of views
  radiogroup = (RadioGroup) findViewById(R.id.radiogroup_OS);

  // set the listeners for the views
  radiogroup.setOnCheckedChangeListener(this);

 }

 @Override
 public void onCheckedChanged(RadioGroup group, int checkedId) {
  // TODO Auto-generated method stub
  radiobutton = (RadioButton) findViewById(checkedId);
  Toast.makeText(this, "You selected: " + radiobutton.getText(),
    Toast.LENGTH_SHORT).show();
 }
}
   

No comments:

Post a Comment