【问题标题】:how to assign defined radio button layout to dynamic radio button如何将定义的单选按钮布局分配给动态单选按钮
【发布时间】:2017-03-31 16:25:10
【问题描述】:

我在activity_main.xml 中为单选按钮定义了xml。在主要活动中,我试图将单选按钮动态添加到单选组。 遇到这个错误

指定的孩子已经有一个父母。您必须首先在孩子的父母上调用 removeView()

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

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>

【问题讨论】:

  • 请提供一个完整的例子。特别是,您应该有一个完整的 Activity 或 Fragment 类,其中包含您所询问的代码(最有可能在 onCreate() 或 onCreateView() 中)。您还应该提供一个完整的 XML 布局文件。这意味着您应该有一个有效的根元素,例如 LinearLayout 或 RelativeLayout。注意这并不意味着发布您的所有代码。您仍然应该只发布与问题相关的内容。

标签: android android-layout android-radiogroup android-radiobutton


【解决方案1】:

那是因为您获得了对在您的 xml 中定义的同一个 RadioButton 的引用。

尝试做:

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

要设置在 xml 中定义的相同属性,您可以通过编程方式进行设置,或者创建新布局并对其进行扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多