简体   繁体   English

Android:单击每个按钮即可创建新的ImageView

[英]Android: Create new ImageView by every button click

I want to generate and add a new ImageView by a button click everytime the button is pressed. 我想通过每次单击按钮时通过单击按钮来生成并添加新的ImageView。 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. 我以为每次单击按钮都会创建一个新的ImageView。 But it obviously doesn't. 但这显然不是。 Is there any other way to create and add an ImageView to the layout by button click? 还有其他方法可以通过单击按钮来创建ImageView并将其添加到布局中吗?

Declare a field previousId in you class private int previousId=0; 在您的课程中声明一个字段previousId private int previousId = 0; You will have to set an incremental id of your image view iv 您将必须设置图像视图的增量ID 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. 这样,每次要求相应的父母添加一个新ID不同于先前的ID的新孩子。

if(view != null) {
    return view; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM