0

我正在尝试在 TableLayout 中插入我的代码中的行。我在互联网和 stackOverflow 上获得了几个教程,以及每次遇到此异常时的一些教程。

12-12 17:54:07.027: E/AndroidRuntime(1295): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

12-12 17:54:07.027: E/AndroidRuntime(1295):     at com.kaushik.TestActivity.onCreate(TestActivity.java:41)

这是活动类:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /* Find Tablelayout defined in main.xml */
        TableLayout tl = (TableLayout) findViewById(R.id.myTableLayout);
        /* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        /* Create a Button to be the row-content. */
        Button b = new Button(this);
        b.setText("Dynamic Button");
        b.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        /* Add Button to row. */
        tr.addView(b);
        /* Add row to TableLayout. */
        tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        /* adding another row */
        TableRow tr2 = new TableRow(this);
        tr2.addView(b); // Exception is here
        tl.addView(tr2, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

这是XML

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/myTableLayout"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
</TableLayout>

请帮我。

4

1 回答 1

0

你做错了

 /* adding another row */
 TableRow tr2 = new TableRow(this);
 tr2.addView(b); // Exception is here

B 是一个按钮,因为它已经添加到您的表格第一行“t1”中。由于按钮是一个视图,每个视图只能由一个父级持有。按钮 b 已显示在第一行。它可以在 row2 上再次显示。

由于当用户单击按钮或row1row2时它没有逻辑,那么如何知道按下了哪个按钮?我的意思是你不知道它是被第 1 行或第 2 行按下的。所以这是你正在做的出乎意料的事情。

如在

onClick(View view){
   if(view == b){
       // So you cant do that this is button row1 button or row2 button.
   }

   // Or you can check the pressed button by id which will also be same. 

}

因此,您应该创建新的 Button button2,然后添加到 row2。

于 2011-12-12T12:54:33.860 回答