I have 16 imageviews on an activity......named img1->img16. I want a diff image on each image view and this cannot be hardcoded, depening on what number is passed as an extra, e.g. 1, 2 , 3..... the images added to these views must be different.
I currently have code that adds 16 images but these are not unique..... they are duplicated...
int[] imageViews = {
R.id.img1, R.id.img2,
R.id.img3, R.id.img4,
R.id.img5, R.id.img6,
R.id.img7, R.id.img8,
R.id.img9, R.id.img10,
R.id.img11, R.id.img12,
R.id.img13, R.id.img14,
R.id.img15, R.id.img16
};
int[] images = {
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8,
R.drawable.img9, R.drawable.img10,
R.drawable.img11, R.drawable.img12,
R.drawable.img13, R.drawable.img14,
R.drawable.img15, R.drawable.img16
};
Random random = new Random(System.currentTimeMillis());
for(int v : imageViews)
{
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[random.nextInt(images.length - 1)]);
}
And also, if possible, i need it so that the images are not hard coded in the images array as they will be different depending on what number has been passed.
So these images are for the number 1, but if number 2 was passed to the activity, the images would be different.
all the details are saved in a local database and the images are all in the drawable folder and will all follow the same naming styles e.g. img1 all the way to say img100....
Many thanks in advance.
/UPDATE/
Hi, I have tried that with the following code:
Random random = new Random(System.currentTimeMillis());
List<Integer> generated = new ArrayList<Integer>();
for(int v : imageViews)
{
int next = random.nextInt(15) + 1;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[next]);
}
}
I may be doing it completely wrong there i guess.... but so far i have not found a duplicate, but does not help with the gaps, its as if it maybe generates 16 random ints but only adds the ones that are unique, rather than generating till reaches 16 unique images if you understand?
Any ideas on that front?