java - 将相同的布局添加到一个容器android

标签 java android

我想在代码中添加相同的布局到相同的布局:

LinearLayout container = (LinearLayout) findViewById(R.id.contactLayout);
for (Info info : contact.getInfo()) {
    View header = getLayoutInflater().inflate(R.layout.item_contact_header, null);
    TextView headerText = (TextView) header.findViewById(R.id.contactHeader);
    headerText.setText(info.getSection());
    container.addView(headerText);
    for (Row row : info.getRows()) {
        View item = getLayoutInflater().inflate(R.layout.item_kontakt_oss, null);
        TextView itemHeader = (TextView) item.findViewById(R.id.itemHeader);
        TextView itemValue = (TextView) item.findViewById(R.id.itemValue);
        ImageView imageIcon = (ImageView) item.findViewById(R.id.imageIcon);
        RelativeLayout relativeLayout = (RelativeLayout) item.findViewById(R.id.mainLayout);
        itemHeader.setText(row.getHeader());
        itemValue.setText(row.getDetails());
        imageIcon.setImageResource(getDrawableForItem(row.getActionType()));
            relativeLayout.setOnClickListener(view -> {
            });
            container.addView(item);
        }
    }

但我收到错误:java.lang.IllegalStateException:指定的子项已经有父项。您必须首先在子级的父级上调用removeView()。

有什么想法可以解决这个问题吗?

最佳答案

您无法添加已经是另一个 View 的 subview 的 View 。在您的情况下, headerText 是 'header' 的子项。 您可以在将 View 整体膨胀后添加 View 。

container.addView(header);

这应该有效。

关于java - 将相同的布局添加到一个容器android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944140/

相关文章:

java - 在另一个服务 Junit 中模拟一个服务的服务

java - Java 6 上的 AtomicInteger getAndUpdate 为零

java - 将多个文本添加到 TextView

android - 将存储在谷歌驱动器中的 PDF 文件显示到 WebView

java - Android - 如何使用身份验证进行 MySQL 数据库事务?

java - 来自 servlet 的 RemoteApi 调用未在本地应用程序引擎应用程序中加载

java - Gradle Jacoco 插件报告零覆盖率

android - 单击按钮开始另一个 Activity

android - 系统重新启动后环境路径设置为 "PATH"变量丢失?

android - 如何在osmdroid中显示当前位置指针?