In this article, I am going to explain how to create two mutually-exclusive (in a group) radio buttons (enabling one disables the other), using the RadioGroup and RadioButton widgets. When either radio button is pressed, a toast message will be displayed.
· Start a new project, named RadioButtonDemo.
· Open the res/layout/main.xml file and add two RadioButtons, nested in a RadioGroup (inside the LinearLayout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton android:id="@+id/radio_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton android:id="@+id/radio_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>
</LinearLayout>
· Now when each RadioButton is selected, you need a View.OnClickListener. so add the following code in the Activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.Toast;
public class RadioButtonActivity extends Activity {
private OnClickListener radioListener= new OnClickListener() {
public void onClick(View v) {
RadioButton rb=(RadioButton)v;
Toast.makeText(RadioButtonActivity.this, rb.getText(),
Toast.
Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final RadioButton radioMale=(RadioButton)findViewById(R.id.radio_male);
final RadioButton radioFemale=(RadioButton)findViewById(R.id.radio_female);
radioMale.setOnClickListener(radioListener);
radioFemale.setOnClickListener(radioListener);
}
}
· Run the application
Your output is something like below:
When any radio button is selected by the user, the radiobutton text will display in the toast message.
Leave Comment