Android RadioButton Example : Getting started with Android

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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>
|
Your Java Code should look like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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());
}
}
}
|
The Output will look like

