Это сделает работу:
int buttons = 5;
RadioGroup rgp = new RadioGroup(getApplicationContext());
for (int i = 1; i <= buttons; i++) {
RadioButton rbn = new RadioButton(this);
rbn.setId(1 + 1000);
rbn.setText("RadioButton" + i);
//Attach button to RadioGroup.
rgp.addView(rbn);
}
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
viewGroup.addView(rgp);
Это полный пример:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Defining buttons quantity!
int buttons = 5;
//Create a new instance of RadioGroup.
RadioGroup rgp = new RadioGroup(getApplicationContext());
//Create buttons!
for (int i = 1; i <= buttons; i++) {
RadioButton rbn = new RadioButton(this);
rbn.setId(1 + 1000);
rbn.setText("RadioButton" + i);
//Attach button to RadioGroup.
rgp.addView(rbn);
}
//Get the root view.
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
viewGroup.addView(rgp);
}
}
И вот результат:
![enter image description here](https://i.stack.imgur.com/CmUjQ.png)
Если вам нужно использовать радиогруппу, определенную в макете xml, и добавлять динамические кнопки, см. этот ответ .