Radio Button
A radio button is a two-states button that can be either checked or unchecked. They are normally used together in a RadioGroup. When several radio buttons live inside a radio group, checking one radio button unchecks all the others.
Example:-
First create a layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<RadioGroup
android:id="@+id/genderRadioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="@+id/knowGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Know Gender" />
</LinearLayout>
Now instantiate UI inside onCreate method of your activity class
// instantiate UI
maleRadioButton = (RadioButton) findViewById(R.id.male);
femaleRadioButton = (RadioButton) findViewById(R.id.female);
submitButton = (Button) findViewById(R.id.knowGender);
Now handle click listener on submitButton
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(maleRadioButton.isChecked())
{
Toast.makeText(Test.this, "Selected gender is Male", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Test.this, "Selected gender is Female", Toast.LENGTH_SHORT).show();
}
}
});
0 Comment(s)