Friday 18 January 2013

RadioButton Demo






1)main.xml:

<?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:background="#ffffff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Select Gender"
        android:textColor="#000000"
        android:textSize="20dp" />

    <RadioGroup
        android:id="@+id/rgGender"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:textColor="#000000" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:textColor="#000000" />
    </RadioGroup>

    <Button
        android:id="@+id/btnGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="Show Gender" />

</LinearLayout>


2)Activity:



package com.venky.radiobutton;

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 RadioButtonDemoActivity extends Activity {
      /** Called when the activity is first created. */
      RadioGroup radioGroup;

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

            radioGroup = (RadioGroup) findViewById(R.id.rgGender);

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

            btnGender.setOnClickListener(new OnClickListener() {

                  public void onClick(View v) {
                        // TODO Auto-generated method stub

                        int id = radioGroup.getCheckedRadioButtonId();
                        RadioButton radioButton = (RadioButton) findViewById(id);
                        String gender = radioButton.getText().toString();

                        Toast.makeText(getApplicationContext(), "Selected " + gender,
                                    5000).show();
                  }
            });

      }
}

3)Download this Project Click Here

No comments:

Post a Comment