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

时间:2015-12-02 06:12:13

标签: android

我想在textview视图中添加checkboxlinearlayout

 for(int i = 0 ; i < helperitems.size() ; ++i){
                    final UserHelper u = helperitems.get(i);


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            LinearLayout linearLayout = new LinearLayout(ContentChatSendMessage.this);
                            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT));
                            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                            linearLayout.setGravity(Gravity.RIGHT);


                            ViewGroup.LayoutParams txt_view_params = new ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                            CheckBox ch = new CheckBox(ContentChatSendMessage.this);
                            ch.setId(Integer.parseInt(u.getId()));
                            linearLayout.addView(ch);

                            TextView textView = new TextView(ContentChatSendMessage.this);
                            textView.setLayoutParams(txt_view_params);
                            textView.setText(u.getUsername1());
                            linearLayout.addView(ch);

                            arr_chs.add(ch);
                            lay_lin_parent.addView(linearLayout);

                        }
                    });

                }

我的布局:

<LinearLayout
...

    <LinearLayout
        android:id="@+id/lay_lin_parent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="10dp"
        android:layout_marginRight="4dp"
        android:layout_marginLeft="4dp">

    </LinearLayout>
...
</LinearLayout>

但是我收到了这个错误:

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

1 个答案:

答案 0 :(得分:2)

您的代码正在尝试将CheckBox ch添加到linearLayout两次。循环中的第二个linearLayout.addView()调用应为:linearLayout.addView(textView);