新手求指教!动态添加RadioButton的错误

晨曦琉璃 2017-07-27 11:20:22
代码部分
public class MainActivity extends AppCompatActivity {
ArrayList<String> totalList=new ArrayList<String>();
Handler ChangeUI_Handler;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent getintent = getIntent();
totalList=getintent.getStringArrayListExtra("totalList");
rg=(RadioGroup)findViewById(R.id.radiogroup);
RadioButton rbtn = new RadioButton(this);
RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,50);
rbtn.setLayoutParams(layoutParams);

for (int t=0;t<=totalList.size();t++){
rbtn.setId(t);
rbtn.setGravity(Gravity.CENTER);
rbtn.setText(totalList.get(t));
rg.addView(rbtn);
}
}


XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


<LinearLayout
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">


<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">

<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">

</RadioGroup>
</HorizontalScrollView>

<ListView
android:id="@+id/Mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />

</LinearLayout>
</android.support.constraint.ConstraintLayout>



addView那行报错java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
求指教怎么修改,谢谢!
...全文
176 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
晨曦琉璃 2017-07-28
  • 打赏
  • 举报
回复
引用 2 楼 u010668114 的回复:

        RadioButton rbtn = new RadioButton(this);
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,50);
        rbtn.setLayoutParams(layoutParams);
这一截代码要放到循环体内,要不你循环里一直添加的是同一个RadioButton,重复添加当然会报错咯
感谢!解决了!
只为搞笑 2017-07-28
  • 打赏
  • 举报
回复

        RadioButton rbtn = new RadioButton(this);
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,50);
        rbtn.setLayoutParams(layoutParams);
这一截代码要放到循环体内,要不你循环里一直添加的是同一个RadioButton,重复添加当然会报错咯
moonFY 2017-07-27
  • 打赏
  • 举报
回复
The specified child already has a parent. You must call removeView() on the child's parent first.

80,354

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧