Add controls to RadioGroup
Description
You can manipulate the RadioGroup
programmatically.
For example, you can obtain a reference to a radio group and add a radio button (or other type of control).
Example
Layout xml
/*from w ww . j a v a2s . co m*/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RadioButton
android:id="@+id/anotherRadBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outside" />
<RadioGroup
android:id="@+id/radGrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/chRBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chicken" />
<RadioButton
android:id="@+id/fishRBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fish" />
<RadioButton
android:id="@+id/stkRBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Steak" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Favorite" />
</RadioGroup>
</LinearLayout>
Adding a RadioButton to a RadioGroup in Code
package com.java2s.app;
//from w w w. j av a2 s .c o m
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
RadioButton newRadioBtn = new RadioButton(this);
newRadioBtn.setText("java2s.com");
radGrp.addView(newRadioBtn);
}
}
Note
Once a radio button is selected within a radio group, the user cannot uncheck it
by clicking it again. The only way to clear all radio buttons in a radio group is to call the
clearCheck()
method on the RadioGroup
programmatically.