【问题标题】:Android: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.Android:java.lang.IllegalStateException:指定的孩子已经有一个父母。您必须首先在孩子的父母上调用 removeView()。
【发布时间】:2011-11-15 07:27:54
【问题描述】:

我正在开发一个 android 应用程序,我在其中动态地制作表格行,然后动态地向它添加 imageviews 和 textviews。 它添加第一行,然后给出以下异常

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

我正在使用以下代码:

          ar1= new JSONArray(children.toString());
                                for(int mn=0;mn<ar1.length();mn++){
                                    value=ar1.getString(mn);
    TableRow tr = new TableRow(HomePageWithPhoneIsOfflineDialog.this);
                                    tr.setBackgroundColor(Color.WHITE);
                                    tr.setId(100+mn);
                                    tr.setMinimumHeight(60);
                                    tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                                    TextView child= new TextView(HomePageWithPhoneIsOfflineDialog.this);
                                    child.setId(200+mn);
                                    child.setHeight(50);
                                    child.setGravity(Gravity.CENTER);
                                    child.setTextColor(Color.BLACK);
                                    System.out.println(value);
                                    child.setText(value);
                                    System.out.println("adding iv");
                                    tr.addView(iv,0);
                                    System.out.println("adding child");
                                    tr.addView(child);
                                    System.out.println("adding table row");
                                     table.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

}

谁能告诉我如何解决这个问题。

谢谢

【问题讨论】:

  • 在哪里抛出异常?
  • 在此处指定位置... tr.addView(child);并不总是一样。

标签: android tablelayout


【解决方案1】:

您要添加的 iv 变量不是在循环内创建的,所以我想是之前创建的......但在第二个循环中,它被添加到两个不同的表行中。

【讨论】:

    【解决方案2】:
    tr.addView(iv,0);
    

    问题在于ImageView (iv),我认为,因为它没有在循环内实例化,所以第一次将它添加到一行,当你再次将它添加到另一行时,它不会允许,因为一个视图只能有 1 个父级。

    所以我建议您在每次循环时创建一个新的 ImageView。

    【讨论】:

      【解决方案3】:

      因为您在每次迭代中添加具有新值的相同视图。

      在tr.addView(iv,0)之前初始化imageView iv;

      ImageView in = new ImageView(ctx)
      

      【讨论】:

        猜你喜欢
        • 2015-09-06
        • 2015-03-20
        • 1970-01-01
        • 2013-10-18
        • 2020-02-16
        • 2014-06-02
        相关资源
        最近更新 更多