java - 动态地将RelativeLayout子级添加到父级布局不起作用

标签 java android android-layout

我试图动态地将 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/

相关文章:

android - 错误 :error: 'drawable/delete.png' is incompatible with attribute android:background (attr) reference|color

android - 在第一个微调器 android 中选择时如何更改第二个微调器数组

java - Gradle 构建文件内的 JAR list 中的 "-includeresource"

java - 检查java中的模式和长度

java - 如何在每次收到来电时启动计时器?

java - 如何制作一个减少数字的函数(例如从 800 毫秒减少到 200 毫秒)

Android 选项菜单应该保留,即使我们点击它下面的 peference 菜单

java - 从中删除单词后重新格式化字符串

android - 在android中使用评级栏

java - LinearLayout 无法转换为 TextView : tutorial Creating Lists and Cards