0
我试图从我的代码中插入TableLayout中的行。我在互联网和stackoverflow上有几个教程,以及每次我得到这个异常的时候。通过TableLayout中的代码插入tablerow时出现异常
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)
这里是activityclass:
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>
请帮助我。
:D那正是我想要的。谢谢谢谢非常感谢。 –
是的,您可以在循环中添加新行,但您必须设法查看。我所说的是创建一个按钮阵列并逐一添加到行 – Arslan