Java 将相同的布局添加到一个容器中
我想将相同的布局添加到代码中的相同布局:Java 将相同的布局添加到一个容器中,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 = (TextVie
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()。
有什么办法可以解决这个问题吗?替换:
GetLayoutFlater().充气(R.layout.item\u contact\u标题,空)
及
getLayoutInflater().充气(R.layout.item\u kontakt\u oss,容器,false);
与
GetLayoutFlater().充气(R.layout.item\u contact\u标题,容器,错误)
getLayoutInflater().充气(R.layout.item\u kontakt\u oss,container,false)
不能添加已经是另一个视图的子视图的视图。headerText在您的案例中是“header”的子级。
可以在将视图整体充气后添加视图
container.addView(header);
这应该行得通。2件事:1。这个错误指向哪一行?2.99%的可能性是,您应该使用
RecyclerView
而不是LinearLayout
。错误行:container.addView(headerText);您的容器线性布局中是否已经有视图?我刚刚用类似的代码创建了一个示例应用程序,没有错误。标题和项目正好添加到LinearLayout中