遍历 ImageViews 并设置随机可绘制对象和可见性

Iterate through ImageViews and set random drawable and visibility

我制作了一个小游戏,但在遍历 ImageView 时遇到了问题。

我有 12 个 ImageView,它们应该随机显示没有苹果、绿色或红色苹果。

如何遍历 ImageView 并设置可见性和可绘制对象? 应用程序崩溃:"App has stopped"

    void shuffleApples() {

    ImageView[] apples = new ImageView[12];
    apples[0] = img_apple1;
    apples[1] = img_apple2;
    apples[2] = img_apple3;
    apples[3] = img_apple4;
    apples[4] = img_apple5;
    apples[5] = img_apple6;
    apples[6] = img_apple7;
    apples[7] = img_apple8;
    apples[8] = img_apple9;
    apples[9] = img_apple10;
    apples[10] = img_apple11;
    apples[11] = img_apple12;

    for(int i = 0; i < apples.length; i++) {
        Random randomAppleVisibility = new Random();
        Random randomAppleColor = new Random();
        int appleVisibility = randomAppleVisibility.nextInt(0);
        int appleColor = randomAppleColor.nextInt(0);

        if(appleVisibility==0) {
            apples[i].setVisibility(View.GONE);
        }
        else {
            if(appleColor==0) {
                apples[i].setImageResource(R.drawable.apple_red);
                redApples++;
            }
            else {
                apples[i].setImageResource(R.drawable.apple_green);
                greenApples++;
            }
        }
    }
}

感谢您的帮助!

如果您想生成 01 的随机整数值,请执行以下操作:

int appleVisibility = randomAppleVisibility.nextInt(2);
int appleColor = randomAppleColor.nextInt(2);

这个

nextInt(0) 

抛出 java.lang.IllegalArgumentException 因为参数必须是正数。
关于 nextInt()

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

你应该考虑加入这些行:

Random randomAppleVisibility = new Random();
Random randomAppleColor = new Random();

for 循环之前。