如何以编程方式多次显示相同的 ImageView?

How to show the same ImageView multiple times programmatically?

我想做一个简单的 "game" 圆圈在一些网格中向上、向下、向左或向右移动(不可点击,只是一个 ImageView)。我想用一个 ImageView

添加多个相同的图像

我已尝试找到最简单的方法,如下所示:

Integer img = R.drawable.trans_grid_2;
ImageView iView = new ImageView(this);
iView.setImageResource(img);

constraintLayout.addView(iView);
constraintLayout.addView(iView); //Cannot add 2 or more of the same Image

这给了我一个错误 (应用程序在启动时崩溃)

   java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

这表明我必须在重新使用它之前调用 removeView() 。但是,我想在 java 中添加多个相同的图像而不需要复杂的东西。我不能多次添加相同的 ImageView

我试过用谷歌搜索这个,但它向我展示了一些复杂的方法,而不是我需要的。

如何在 java 中添加 2 个或更多相同的 ImageView?

你可以这样做:

Integer img = R.drawable.trans_grid_2;
int NUMBER_OF_IMAGES = 2;
for(int i = 0; i < NUMBER_OF_IMAGES; i++) {
    ImageView iView = new ImageView(this);
    iView.setImageResource(img);

    constraintLayout.addView(iView);
}

您只能将一个视图的实例添加到一个父级。