-1
rd1 = (RadioButton) findViewById(R.id.rd1);
rd2 = (RadioButton) findViewById(R.id.rd2);
rd3 = (RadioButton) findViewById(R.id.rd3);
rd4 = (RadioButton) findViewById(R.id.rd4);

RadioGroup rg = new RadioGroup(this);
rg.addView(rd1);
rg.addView(rd2);
rg.addView(rd3);
rg.addView(rd4);
rd1.setChecked(true);

The error is : You must call removeview() on the child's parent first.... Some one help me...

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
  • If the `RadioButton`s are defined in your layout, why not just put them in a `RadioGroup` there? That is, why are you trying to do that in code? – Mike M. Feb 22 '17 at 04:19
  • Because every radiobutton is in a different table row. It's such a quiz test. Can u help me the solution.. – K9_HCM ng Ngc Trung Feb 22 '17 at 05:50
  • Have a look here for ideas: http://stackoverflow.com/questions/10461005/how-to-group-radiobutton-from-different-linearlayouts – Mike M. Feb 22 '17 at 06:22

1 Answers1

3

The problem is your views are created in XML (which is why you must use findViewById)

This means they are already attached to the parent node in the XML tree where you defined them.

You have two options:

The right way is to define the RadioGroup in the XML, either with the Radios inside, or then programatically create and add the radios

or the bad (quick but hacky) way is:

rd1 = (RadioButton) findViewById(R.id.rd1);
...

((ViewGroup) rd1.getParent()).removeView(rd1);
...

RadioGroup rg = new RadioGroup(this);
rg.addView(rd1);
...
rd1.setChecked(true);
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124