samedi 1 décembre 2018

Iterate through ImageViews and set random drawable and visibility

I make a little game and have a problem iterating through ImageViews.

I have 12 ImageViews, which should show randomly no apple, a green or a red apple.

How can i iterate through ImageViews and set Visibility and drawable? The App crashes: "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 randomAppleVisiblity = new Random();
        Random randomAppleColor = new Random();
        int appleVisibility = randomAppleVisiblity.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++;
            }
        }
    }
}

thank you for your help!




Aucun commentaire:

Enregistrer un commentaire