Aung Lay
Aung Lay

Reputation: 13

How to create Random array list and set image id to them

I am new to android programming. I am trying to create a game which has 100 images (img1,img2,...,img100). I want is - everytime on start play (onCreate), I want it to be shuffled order (1st time - img23,img1,img98,....) (2nd Time - img90,img23,....) Just like this.

How can it be done ! Thank you in advance .

I put them into my relativelayout background resource, not in ImageView.

   rl.setBackgroundResource(R.drawable.img1);

Upvotes: 0

Views: 96

Answers (1)

Remy Cilia
Remy Cilia

Reputation: 2623

Here is a simple method to shuffle an array:

public void shuffleArray(int[] ar) {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--) {
        int index = rnd.nextInt(i + 1);
        // Simple swap
        int a = ar[index];
        ar[index] = ar[i];
        ar[i] = a;
    }
}

In your case, you could do something like this:

int[] resourceIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
this.shuffleArray(resourceIds);

Upvotes: 0

Related Questions