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

时间:2018-12-01 14:28:48

标签: android random imageview visibility

我做了一个小游戏,在遍历ImageViews时遇到问题。

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

我如何遍历ImageViews并设置“可见性”和“可绘制”? 应用程序崩溃:“应用程序已停止”

    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++;
            }
        }
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果要产生01的随机整数,请执行以下操作:

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

nextInt(0) 

抛出java.lang.IllegalArgumentException,因为自变量必须为正数。
关于nextInt()

  

返回一个伪随机数,其int值均匀分布在0之间   (含)和指定值(不含)

您应该考虑放置以下行:

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

for循环之前。