I want to generate and add a new ImageView by a button click everytime the button is pressed. This is my code:
entwicklungskarte.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImageView iv = new ImageView(getApplicationContext());
iv.setImageResource(R.drawable.erfindungek);
ResourcenActivity.entwicklungskarten.add(iv);
}
});
But when I click on the button twice, I get this error:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
I thought that it would create a new ImageView by every button click. But it obviously doesn't. Is there any other way to create and add an ImageView to the layout by button click?
Declare a field previousId in you class private int previousId=0; You will have to set an incremental id of your image view iv
iv.setId(++previousId);
before
ResourcenActivity.entwicklungskarten.add(iv);
So that every time the corresponding parent is asked to add a new child with different ID than the previous one.