i am using 9 image view's i want set images to imageview randomly , when I click on refresh button, but I tried like this it's working for random allocation of images but it's repeating the same image in two (or) three imageview's at a time. where is the problem in my code..
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13,
R.id.imgview21, R.id.imgview22, R.id.imgview23,
R.id.imgview31, R.id.imgview32, R.id.imgview33 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3,
R.drawable.i4, R.drawable.i5, R.drawable.i6,
R.drawable.i7, R.drawable.i8, R.drawable.empty };
final ImageButton shuffle = (ImageButton) findViewById(R.id.new_puzzle);
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random generator = new Random();
//int n = 9;
//n = generator.nextInt(n);
//Random random = new Random(System.currentTimeMillis());
for(int v : imageViews) {
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[generator.nextInt(images.length - 1)]);
}
}
});
i don't want repeat, one image for one imageview only..
Maybe not the perfect answer, but I would just shuffle the images list and the set the resulting image to the imageview.
This will avoid having to generate random numbers that will of course create duplicate (If you throw a dice 6 times, you won't have the numbers 1,2,3,4,5,6 in random order, you will get multiple time the same number.)
Please check everything including the 'i' as I am not in front of my computer.
as an alternative, you may also want to shuffle your list with this code:
using the post of blessenm ,i wrote a similar code that you need. check if this helps you.
You might want to refer to this post. It shows a method to generate random numbers without duplicates Creating random numbers with no duplicates