I am new to android development. I want to create RadioButton group programmetically in java class and set the text to the individual radio buttons. Please Help on this
Thanks in Advance.
I am new to android development. I want to create RadioButton group programmetically in java class and set the text to the individual radio buttons. Please Help on this
Thanks in Advance.
This program block shows how to create RadioButton group programmatically.
Hope it will help you.
public class RadioGroupActivity extends Activity {
protected static final String TAG = "RadioGroupActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup);
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
int checkedRadioButtonID = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
switch(id) {
case -1:
Log.v(TAG, "Choices cleared!");
break;
case R.id.chRBtn:
Log.v(TAG, "Chose Chicken");
break;
case R.id.fishRBtn:
Log.v(TAG, "Chose Fish");
break;
case R.id.stkRBtn:
Log.v(TAG, "Chose Steak");
break;
default:
Log.v(TAG, "Huh?");
break;
}
}});
}
}
You have good example here:
Creating RadioButtons programmatically
or this example also good:
Programmatically-added RadioButtons refuse to obey LayoutParams weighting
Here you have it...
ln = (LinearLayout)findViewById(R.id.Linear_layout); // Assuming linearLayout is your parent layout
RadioGroup rg = new RadioGroup(context); // create the RadioGroup
rg.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
cg_Value = new String{“item 1”, “item 2”, “item 3”};
rb = new RadioButton[cg_Value.length];
rg.setOrientation(RadioGroup.HORIZONTAL);// horizontal or vertical depends on requirement
for (int l = 0; l < cg_Value.length; l++) {
rb[l] = new RadioButton(context);
rg.addView(rb[l]); // the RadioButtons are added to
// the radioGroup instead of the
// layout
rb[l].setTextColor(Color.BLACK);
rb[l].setText(cg_Value[l]);
rb[l].setTextSize(14);
}
//rb[1].setChecked(true);
ln.addView(rg);
Hope this helps