I have Radio buttons that are created dynamically.
LinearLayout linLayRoot = (LinearLayout)dialogView.findViewById(R.id.dialog_layout_root);
RadioGroup radGp = new RadioGroup(this);
linLayRoot.addView(radGp);
for (String dir : dirArray)
{
LinearLayout linLayNew = new LinearLayout(this);
linLayNew.setGravity(0x10);
RadioButton radBut = ne开发者_JAVA百科w RadioButton(this); /// <- this button does not work!
radBut.setText("");
TextView tv = new TextView(this);
tv.setText(dir);
tv.setPadding(10, 0, 20, 0);
ImageView ivs = new ImageView(this);
linLayNew.addView(radBut);
linLayNew.addView(tv);
linLayNew.addView(ivs);
radGp.addView(linLayNew);
}
RadioButton radBut1 = new RadioButton(this); /// <- this button works!
radBut1.setId(11);
radBut1.setText("a1");
radGp.addView(radBut1);
RadioButton radBut2 = new RadioButton(this); /// <- this button works!
radBut2.setId(12);
radBut2.setText("b2");
radGp.addView(radBut2);
radGp.setOnCheckedChangeListener( new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getApplicationContext(), String.valueOf(checkedId) , Toast.LENGTH_SHORT).show();
}
});
But as you can see from the comments above, they don't really work, i.e. seems that they aren't binded to the radGp... maybe its because they are in a separate linlearlayout?
Thanks!
the RadioGroup has an addView which takes a view as input. from here it seems you can add the LinearLayout as a child. and the RadioGroup is really a LinearLayout.
UPDATE
i checked the source of RadioGroup.java
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (child instanceof RadioButton) {
final RadioButton button = (RadioButton) child;
if (button.isChecked()) {
mProtectFromCheckedChange = true;
if (mCheckedId != -1) {
setCheckedStateForView(mCheckedId, false);
}
mProtectFromCheckedChange = false;
setCheckedId(button.getId());
}
}
super.addView(child, index, params);
}
this clearly shows that if we nest the radio then it will not work. so i guess, you have to go manual no other way.
Add your RadioButtons
in a List<RadioButton>
and you can check them then by using
mRadioList.get(i).setChecked(true);
You can add them to a List as Ovidiu suggests, but since they are not in a RadioGroup, except for setting checked the RadioButton at position i, you should setChecked(false) to all other RadioButtons.
精彩评论