Android RadioButton Example

RadioButton is used to select any one option from the given group.

In Android by using RadioGroup only we can use RadioButton. We can add any number of RadioButtons to a single RadioGroup. we can add any number of RadioGroup to a single Layout.

RadioButton Example :-

Your XML Code should look like

[sourcecode language="xml"]

<?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">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:text="APK Extension?" />
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/QueGroup1">
<RadioButton android:checked="false"
android:id="@+id/option1" android:text="Android Package"/>
<RadioButton android:checked="false"
android:id="@+id/option2" android:text="Android Platform"/>
</RadioGroup>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Selected is : "></TextView>
<Button android:layout_width="100px"
android:layout_height="wrap_content" android:text="Confirm Selection" android:id="@+id/selected"/>
</LinearLayout>
</LinearLayout>

[/sourcecode]

Your Java Code should look like

[sourcecode language="java"]

public class RadioButtonExample extends Activity implements Button.OnClickListener
{
private RadioButton rb1;
private RadioButton rb2;
private Button b1;
private TextView t1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1=(RadioButton)findViewById(R.id.option1);
rb2=(RadioButton)findViewById(R.id.option2);
b1=(Button)findViewById(R.id.selected);
b1.setOnClickListener(this);
t1=(TextView)findViewById(R.id.TextView01);
}

@Override
public void onClick(View v) {
if(v == b1)
{
if(rb1.isChecked() == true)
t1.setText("Selected is : "+rb1.getText());
if(rb2.isChecked() == true)
t1.setText("Selected is : "+rb2.getText());
}
}
}

[/sourcecode]

The Output will look like

radiobuttonexample

Comments

Hi Vikrant, Thanks for your

Hi Vikrant,
Thanks for your comments :)

Hi Chaits, I think this is

Hi Chaits,
I think this is not possible in android default radio button. But we can customize it to get.

Yes. You are right, we are

Yes. You are right, we are not using any String.xml file here.
If we are using we will surely post for you guys to copy easily & test it.. :)