将RelativeLayout子项添加到父布局动态不起作用

时间:2015-09-27 15:39:06

标签: java android android-layout

我正在尝试动态地将子视图扩展到父视图,但它会引发错误。

我正在尝试将每个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
}

我得到的错误:

  

引起:java.lang.IllegalStateException:指定的子级   已经有了父母。您必须在孩子的父母上调用removeView()   第一。在   com.hellotest.TestingDynamics.onCreate(TestingDynamics.java:43)

第43行指向这一行:

parent.addView(child);

我做错了什么?如果我错了,我的代码有什么改动,伙计们?

1 个答案:

答案 0 :(得分:0)

findViewById

事实并非如此。 RelativeLayout会返回现有的子项,该项已存在于布局中。您必须使用其构造函数创建新的RelativeLayout child = new RelativeLayout(this);

def params = [param1:'val1', param2:'val2':, param3:'val3'] g.V.filter{ params.every {key, value -> it[key] == value } }