Вопрос

I'm creating RadioButtons programmatically

RadioGroup group = (RadioGroup)findViewById(R.id.grp); 
for(int i = 0; i < 3; i++) {
  RadioButton btn = new RadioButton(this); //this is an Activity
  btn.setText(String.valueOf(i));
  group.addView(btn);
}

However, my RadioButtons are not grouped together - I can check all of them, they act independently.

The documentation only states that the RadioGroup is used to create a multiple-exclusion scope for a set of RadioButtons.

Or do I have to manage my RadioButtons' checked state manually?

Это было полезно?

Решение

Every RadioButton requires a unique ID so, that RadioGroup can differentiate them. Try this.

RadioGroup group = (RadioGroup)findViewById(R.id.grp); 
for(int i = 0; i < 3; i++) {
  RadioButton btn = new RadioButton(this);
  btn.setId(i); // <- set ID
  btn.setText(String.valueOf(i));
  group.addView(btn);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top