Header Ads

ad728
  • Breaking News

    Radio Button Example

    RadioButton Example
    main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <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="com.blogspot.csdevbin.radiobutton.Main">
     <RadioGroup
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:id="@+id/genderRadioGrp">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="male"
            android:id="@+id/radioButton"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="95dp"
            android:checked="false" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="female"
            android:id="@+id/radioButton2"
            android:checked="false"
            android:layout_below="@+id/radioButton"
            android:layout_alignLeft="@+id/radioButton"
            android:layout_alignStart="@+id/radioButton" />
     </RadioGroup>
    </RelativeLayout>
    Main.java
    package com.blogspot.csdevbin.radiobutton;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;
    
    public class Main extends AppCompatActivity {
    
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            RadioGroup rg = (RadioGroup) findViewById(R.id.genderRadioGrp);
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    RadioButton radioButton = (RadioButton) findViewById(checkedId);
                    String gender = radioButton.getText().toString();
                    Toast.makeText(Main.this, "Selected gender is :" + gender, Toast.LENGTH_SHORT)
                            .show();
                }
            });
    
        }
    }

    No comments

    Post Top Ad

    ad728

    Post Bottom Ad

    ad728