【问题标题】:Adding RelativeLayout Child to a Parent Layout Dynamically does not work将 RelativeLayout Child 动态添加到父布局不起作用
【发布时间】: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


    【解决方案1】:

    RelativeLayout child = (RelativeLayout) findViewById(R.id.work_list); //new child

    这不是真的。 findViewById 返回 existing 子元素,它已经在布局中。您必须使用其构造函数创建新的RelativeLayout

    RelativeLayout child = new RelativeLayout(this);

    【讨论】:

    • 消除了错误,但我现在在视图中看不到子布局。看起来他们没有膨胀:/
    • 哦,当然什么都没有出现,我还没有将布局设置为膨胀:D 我该怎么做?
    • @Earthling 您已接受答案 - 您还需要帮助吗?膨胀是使用构造函数创建布局的替代方法,因此如果您以编程方式创建布局,则不需要膨胀布局。我会说你没有(没有)看到它们,因为它们是空的,它们的大小设置为 WRAP_CONTENT
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多