gpt4 book ai didi

Android:您必须先在 child 的 parent 身上调用 removeView() 2

转载 作者:行者123 更新时间:2023-11-29 16:02:14 26 4
gpt4 key购买 nike

我在 Android 创建动态添加行的表时遇到问题。错误信息是:

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

但为什么呢?

    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 添加此 View

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);

关于Android:您必须先在 child 的 parent 身上调用 removeView() 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com