我在Android
创建动态添加行的表时遇到问题。错误消息是:
指定的孩子已经有一个父母。您必须调用removeView()
首先在孩子的父母身上
但为什么?
void setCalendario(List<ArrayList<String>> l){
TableLayout table = (TableLayout)findViewById(R.id.list_tableLayout1);
TableRow tr = new TableRow(this);
tr.removeAllViews();
tr.setPadding(0,10,0,10);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView tv_item1 = new TextView(this);
TextView tv_item2 = new TextView(this);
TextView tv_item3 = new TextView(this);
for (ArrayList<String> al : l){
int i = 0;
for(String s : al){
if (i == 0){
i++;
tv_item1.setText(s);
tv_item1.setGravity(Gravity.CENTER);
}
if (i == 1){
tv_item2.setText(s);
tv_item2.setGravity(Gravity.CENTER);
i++;
}
if (i == 2){
tv_item3.setText(s);
tv_item3.setGravity(Gravity.CENTER);
tr.addView(tv_item1);
tr.addView(tv_item2);
tr.addView(tv_item3);
table.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
}
}
xml代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.MSca.gorhinos.Calendario$PlaceholderFragment" >
<TableLayout
android:id="@+id/list_tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:stretchColumns="0,1,2,3" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000000"/>
</TableRow>
</TableLayout>
</RelativeLayout>
最佳答案
因此,您一次创建了tv_item1,tv_item2和tv_item3。然后为所有ArrayList循环添加此视图
tr.addView(tv_item1);
tr.addView(tv_item2);
tr.addView(tv_item3);
在第二次迭代中,您已经将tv_item1添加到tr中。您想再做一次。我想您只需要将此行转移即可循环:
TableRow tr = new TableRow(this);
tr.removeAllViews();
tr.setPadding(0,10,0,10);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv_item1 = new TextView(this);
TextView tv_item2 = new TextView(this);
TextView tv_item3 = new TextView(this);