I’m having trouble in making unrepeating random images on my Android App.
Let’s say on my App I have this TOP 3 Sections, and I have 13 pictures. I need a method to generate 3 random images from the 13 pics on @drawable I have, but the 3 pictures should be different from one another.
For example: it can’t be img1,img1,img2 or img1,img1,img1 on the TOP 3 section but it should be img1,img2,img3.
So far, I have this method in hand:
final Button imgView = (Button)findViewById(R.id.top1);
Random rand = new Random();
int rndInt = rand.nextInt(13) + 1;
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
On my layout, I specified one of the image ID on the TOP 3 section as top1. I still have the id top2, and top3 for the TOP 3 section. The above code will look up to my drawable images, which have the names ‘img1.jpg’, ‘img2.jpg’, ‘img3.jpg’ , ‘img4.jpg’, etc.
I’m open to any kind of solution. If somebody could improvise my code so 3 pictures won’t be the same with each other that would be perfect. But if any of you can offer a better solution with a new method, I’m open for it.
Thank you.
I’d suggest you to store your image ids in
List, use shuffleand retrieve the first element by removing.
EDIT:
The initialization of list should be performed once, outside of image add method (somewhere in
onCreateprobably.