sarath
sarath

Reputation: 157

adding Radiobutton's dynamically

my XML file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" 
android:id="@+id/sl"
>


<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rgc">
 </RadioGroup>


</LinearLayout>

Java file

LinearLayout l1;
RadioGroup rg;
RadioButton rb[];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    l1=(LinearLayout)findViewById(R.id.sl);
    rg=(RadioGroup)findViewById(R.id.rgc);


    rb=new RadioButton[4];
    for(int i=0;i<4;i++){
        rb[i]=new RadioButton(this);
        rb[i].setLayoutParams(new LinearLayout.LayoutParams(60,30));
        rb[i].setText(i+"aaaaaa");
        rg.addView(rb[i]);

    }

    l1.addView(rg);



}

when I am running this code getting exception "this specified child already has a parent".Please tell me friends what is the problem in my code and kindly give me any suggestion's.

Upvotes: 0

Views: 257

Answers (2)

Kiran Babu
Kiran Babu

Reputation: 1893

Try this code, Hope it will help

RadioGroup rg=(RadioGroup)findViewById(R.id.rgc);
        RadioButton rb;

        for(int i=0;i<4;i++)
        {
            rb=new RadioButton(this);
            rb.setText(i+"aaaaaa");
            rg.addView(rb,i,new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

        }

        rg.invalidate(); 

Upvotes: 0

ekjyot
ekjyot

Reputation: 2227

Just dont add rg to linear layout As it radiogroup is already present in the linearlayout in the xml file

Upvotes: 2

Related Questions