Hafiz Fahad Munir
Hafiz Fahad Munir

Reputation: 527

how to assign defined radio button layout to dynamic radio button

I have defined xml for radio button in activity_main.xml. In main activity i am trying to add radio buttons to radio group dynamically. facing this error

The specified child already has a parent. You must call removeView() on the child's parent first

RadioGroup answerOptions = (RadioGroup) findViewById(R.id.answers_options);


    for (int i = 0; i < answersList.size() ; i++) {
        RadioButton radioButton = new RadioButton(MainActivity.this);
        radioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
        radioButton.setText(answersList.get(i).getOption_description());
        answerOptions.addView(radioButton,i);
    }

some part of main_activity.xml

    <RadioGroup

        android:id="@+id/answers_options"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_weight="1">

        <RadioButton
            android:textSize="22sp"
            android:id="@+id/simpleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.20"
            android:text=""
            android:layout_gravity="left" />

    </RadioGroup>

Upvotes: 1

Views: 94

Answers (1)

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

That's because you are getting a reference to the same RadioButton that is defined in your xml.

Try doing:

for (int i = 0; i < answersList.size() ; i++) {
    RadioButton radioButton = new RadioButton(MainActivity.this);
    radioButton.setText(answersList.get(i).getOption_description());
    answerOptions.addView(radioButton,i);
}

To set the same properties defined in xml you could do it programmatically or create a new layout and inflate it.

Upvotes: 1

Related Questions