我正在尝试在 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>
请帮我。