【发布时间】:2015-09-27 15:39:05
【问题描述】:
我正在尝试动态地将子视图膨胀到父视图,但它会引发错误。
我正在尝试将每个 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: 指定的孩子 已经有了父母。您必须在孩子的父母上调用 removeView() 第一的。在 com.hellotest.TestingDynamics.onCreate(TestingDynamics.java:43)
第 43 行指向这一行:
parent.addView(child);
我做错了什么?如果我错了,我的代码的更正是什么,伙计们?
【问题讨论】:
标签: java android android-layout