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

时间:2017-05-12 18:16:17

标签: 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: The specified child already has a parent. You must call removeView() on the child's parent first.

任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您无法添加已经是另一个视图的子视图。 headerText是'标题'的孩子。在你的情况下。 您可以在将视图作为一个整体充气后添加视图。

container.addView(header);

这应该有效。

答案 1 :(得分:0)

替换:

getLayoutInflater().inflate(R.layout.item_contact_header, null)

getLayoutInflater().inflate(R.layout.item_kontakt_oss, container, false);

getLayoutInflater().inflate(R.layout.item_contact_header, container, false) getLayoutInflater().inflate(R.layout.item_kontakt_oss, container, false)