How to set random images to ImageView's?

≡放荡痞女 提交于 2019-11-29 08:21:12

using the post of blessenm ,i wrote a similar code that you need. check if this helps you.

shuffle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) { 

            Random rng = new Random(); 
            List<Integer> generated = new ArrayList<Integer>();
            for (int i = 0; i < 9; i++)
            {
              while(true)
              {
                 Integer next = rng.nextInt(9) ;
                 if (!generated.contains(next))
                 {
                    generated.add(next);
                    ImageView iv = (ImageView)findViewById(imageViews[i]);
                    iv.setImageResource(images[next]);
                    break;
                 }
               }
            }
            }
        });

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.

List<int> list = Arrays.asList(images);
// Here we just simply used the shuffle method of Collections class
// to shuffle out defined array.
Collections.shuffle(list);

int i=0;
// Run the code again and again, then you'll see how simple we do shuffling
for (int picture: list) {
    ImageView iv = (ImageView)findViewById(imageViews[i]);
    iv.setImageResource(picture);
    i++;
}

as an alternative, you may also want to shuffle your list with this code:

public class ShuffleArray {
    public static void shuffleArray(int[] a) {
        int n = a.length;
        Random random = new Random();
        random.nextInt();
        for (int i = 0; i < n; i++) {
            int change = i + random.nextInt(n - i);
            swap(a, i, change);
        }
    }

    private static void swap(int[] a, int i, int change) {
        int helper = a[i];
        a[i] = a[change];
        a[change] = helper;
    }

    public static void main(String[] args) {
        int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        shuffleArray(a);
        for (int i : a) {
            System.out.println(i);
        }
    }
}
blessenm

You might want to refer to this post. It shows a method to generate random numbers without duplicates Creating random numbers with no duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!