代码:
maxIndex = alItemListDetails.size();
linItemTags = (LinearLayout) findViewById(R.id.linItemTags);
final ImageView image = new ImageView(this);
for (int i = 0; i < maxIndex; i++) {
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80, 60));
image.setMaxHeight(20);
image.setMaxWidth(20);
image.setTag(i);
image.setImageResource(R.drawable.box);
// Adds the view to the layout
linItemTags.addView(image);
}
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Common.displayToast(ItemDetailsActivity.this, "" + image.getTag());
}
});
从上面的代码中,您可以看到我已动态生成了imageview并尝试处理该Imageview的点击事件。
但是,它给我的错误如下:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
答案 0 :(得分:2)
引起:java.lang.IllegalStateException:指定的子级 已经有了父母。您必须在孩子的父母上调用removeView() 第一
因为在ImageView
版面中添加了相同的image
对象linItemTags
,所以
在for循环中创建image
对象:
for (int i = 0; i < maxIndex; i++) {
ImageView image = new ImageView(this); //<< create here
....
linItemTags.addView(image);
}
答案 1 :(得分:2)
try this
maxIndex = alItemListDetails.size();
linItemTags = (LinearLayout) findViewById(R.id.linItemTags);
for (int i = 0; i < maxIndex; i++) {
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80, 60));
image.setMaxHeight(20);
image.setMaxWidth(20);
image.setTag(i);
image.setImageResource(R.drawable.box);
// Adds the view to the layout
linItemTags.addView(image);
image.setOnClickListener(new ImageClickLIstener(i));
}
class ImageClickLIstener implements OnClickListener
{
int position;
ImageClickLIstener()
{
this.position= position;
}
@Override
public void onClick(View v) {
Common.displayToast(ItemDetailsActivity.this, "" + position);
}
}