我试图动态地将 subview 膨胀为父 View ,但它会引发错误。
我正在尝试将每个relativelayout子项添加到另一个下面
这是我的代码:
父布局
<RelativeLayout
android:id="@+id/work_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</RelativeLayout>
子布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<ImageView
android:id="@+id/work_pic"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/image_placeholder"/>
</RelativeLayout>
通货膨胀代码:
RelativeLayout parent = (RelativeLayout) findViewById(R.id.work_list);
//array containing all children ids
ArrayList<Integer> children = new ArrayList<>();
//adding 10 children to the parent
for(int i=0;i<10;i++) {
RelativeLayout child = (RelativeLayout) findViewById(R.id.work_list); //new child
child.setId(i); //setting an id for the child
children.add(i); //adding the child's id to the list
if(i!=0) //if it isn't the 1st child, stack them below one another, since the 1st child does not have a child to stack below
{
RelativeLayout.LayoutParams params
= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, children.get(i - 1)); //stack it below the previous child
child.setLayoutParams(params);
}
parent.addView(child); //add the new child
}
我得到的错误:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at com.hellotest.TestingDynamics.onCreate(TestingDynamics.java:43)
第 43 行指向此行:
parent.addView(child);
我做错了什么?如果我错了,伙计们,我的代码的修正是什么?
最佳答案
RelativeLayout child = (RelativeLayout) findViewById(R.id.work_list);//新 child
这不是真的。 findViewById
返回已存在于布局中的现有子项。您必须使用其构造函数创建新的 RelativeLayout
:
RelativeLayout child = newrelativelayout(this);
关于java - 动态地将RelativeLayout子级添加到父级布局不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809687/