4

I want to create RadioGroup, with RadioButton list inside it, in the onCreate function. I want to do it as exercise w/o using xml-layout. Is it possible? Thanks.

tatiana_c
  • 948
  • 7
  • 16
  • 31
  • Possible duplicate of [How to add radio button dynamically as per the given number of counts?](https://stackoverflow.com/questions/19380526/how-to-add-radio-button-dynamically-as-per-the-given-number-of-counts) – Mehdi Dehghani Jul 25 '18 at 09:05

2 Answers2

4

Something like this:

....
RadioGroup group = new RadioGroup(this); 
group.setOrientation(RadioGroup.HORIZONTAL);
RadioButton btn1 = new RadioButton(this);
btn1.setText("BTN1");
group.addView(btn1);
RadioButton btn2 = new RadioButton(this);
group.addView(btn2);
btn2.setText("BTN2");
.... 
RadioButton btnN = new RadioButton(this);
group.addView(btnN);
btnN.setText("BTNN");
yourLayout.addView(group);
....
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34
3

This will do the job:

    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);

This is a complete example:

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);


    }
}

And this is the result:

enter image description here

If you need to use a RadioGroup defined into the xml layout and add dinamically buttons see this answer.

Community
  • 1
  • 1
Jorgesys
  • 124,308
  • 23
  • 334
  • 268