Wednesday, 13 November 2013

RadioButton in Android

Here i'm giving another example on RadioButton.

Output Screen Shots:




Project Name: WorkingwithRadioButton
XML files : activity_main.xml
Java files:MainActivity.java
values folder files: strings.xml 



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

    <string name="app_name">working with RadioButton</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="radio_male">Male</string>
    <string name="radio_female">Female</string>

</resources>

 activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="46dp" >

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

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

</LinearLayout>

MainActivity.java:
package com.ram.workingwithradiobutton;

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 {

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

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

// Register a callback to be invoked when the checked radio button  changes in this group.

rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

RadioButton rb = (RadioButton) findViewById(checkedId);

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

Toast.makeText(getApplicationContext(), gender,
Toast.LENGTH_LONG).show();
}
});
}

}