Question

I have several image views and several images to add to a layout and i add them randomnly, i need to make sure two image views don not contain the same image...here is my for loop for dynamically adding images to the image views.

     Random random = new Random(System.currentTimeMillis());

        for(int v : imageViews) {

            ImageView iv = (ImageView)findViewById(v);
            iv.setImageResource(images[random.nextInt(images.length-1)]);

        }

I found a way to do this and i am going to add the editted code:

     LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.bottomView);

        for(int x=0;x<images.length;x++) {
            Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),images[x]);

            int width = bitmapOrg.getWidth();
            int height = bitmapOrg.getHeight();
            int newWidth = 200;
            int newHeight = 200;

            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;

            Matrix matrix = new Matrix();

            matrix.postScale(scaleWidth, scaleHeight);
            matrix.postRotate(0);

            Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                          width, height, matrix, true);
            BitmapDrawable bmd = new BitmapDrawable(getResources(),resizedBitmap);

            ImageView imageView = new ImageView(this);
            imageView.setPadding(2, 0, 9, 5);
            imageView.setImageDrawable(bmd);
            imageView.setTag(x);

            imageView.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_VIEW); 

                }
            });

            linearLayout1.addView(imageView);
        }
Was it helpful?

Solution

The easiest way would be to have the images as List<> instead of an array, and call Collections.shuffle(images, random) before the loop starts. That way you are guaranteed no repeats, just by picking the images sequentially.

This would be a very good solution especially if the image collection isn't exceedingly large (otherwise you could be shuffling a very large list to pick just a small subset of it).

If the collection is large, then you could just keep a HashSet with the positions already picked, and make sure that a new image is selected each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top