下面的循环如果运行一次 (n = 1) 就可以工作,但会在多次执行 (n > 1) 时崩溃。
IllegalStateException:指定的子项已经有一个父项。您必须首先对 child 的 parent 调用 removeView()。在“containerLL.addView(divider);”行
在此循环中还有其他使用“new”创建的 View ,但与手头的问题无关。
我不确定我是否需要制作一个“新的”RelativeLayout 每次或什么是修复它的正确方法。
谢谢
分隔符.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/divider_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/plan_divider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="?android:attr/listDivider" />
LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
for(int i = 0; i<n ; i++){
LayoutInflater li = LayoutInflater.from(activity);
RelativeLayout rl = (RelativeLayout) activity.findViewById(R.id.divider_parent);
View divider = li.inflate(R.layout.divider, rl);
containerLL.addView(divider);
}
最佳答案
试试这个。
LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
for(int i = 0; i<n ; i++){
LayoutInflater li = LayoutInflater.from(activity);
View divider = li.inflate(R.layout.divider, null, false);
containerLL.addView(divider);
}
关于android - 以编程方式在同一容器中多次添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751135/