Wednesday, 26 August 2015

RadioButton in Android

activity_main.xml
------------------
<LinearLayout 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:orientation="vertical"
   
tools:context=".MainActivity">
  <
RadioGroup
     
android:layout_width="fill_parent"
     
android:id="@+id/helloradio"
     
android:layout_height="wrap_content"
     
android:weightSum="1"
     
android:layout_marginTop="25dp">
      <
RadioButton
          
android:layout_width="wrap_content"
         
android:id="@+id/radio1"
         
android:text="Male"
         
android:layout_height="wrap_content"
         
/>
      <
RadioButton
         
android:layout_width="wrap_content"
         
android:id="@+id/radio2"
         
android:text="FeMale"
         
android:layout_height="wrap_content" />
  </
RadioGroup>

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


</
LinearLayout>

MainActivity.Java
--------------------
package com.android.anil.radiobutton;



import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

    RadioGroup rg;

    RadioButton rb;

    Button genderbtn;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        rg=(RadioGroup)findViewById(R.id.helloradio);

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

        genderbtn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                int id=rg.getCheckedRadioButtonId();

                rb=(RadioButton)findViewById(id);

              String s1=rb.getText().toString();

           Toast.makeText(getApplicationContext(),"Gender is : "+s1,5000).show();

            }

        });  

   }

}

OutPut is :
----------------










No comments:

Post a Comment