【问题标题】:How to check so imageviews don't contain same image如何检查图像视图不包含相同的图像
【发布时间】:2014-06-28 06:22:25
【问题描述】:

我有几个图像视图和几个图像要添加到布局中,我随机添加它们,我需要确保两个图像视图不包含相同的图像...这是我的 for 循环,用于将图像动态添加到图像视图。

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

        for(int v : imageViews) {

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

        }

我找到了一种方法,我将添加编辑后的代码:

     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);
        }

【问题讨论】:

    标签: android for-loop random imageview


    【解决方案1】:

    最简单的方法是将图像作为 List 而不是数组,并在循环开始之前调用 Collections.shuffle(images, random)。这样一来,您就可以保证不会重复,只需按顺序选择图像即可。

    这将是一个非常好的解决方案,尤其是在图像集合不是特别大的情况下(否则您可能会洗牌一个非常大的列表以仅选择其中的一小部分)。

    如果集合 很大,那么您可以只保留一个包含已选择位置的 HashSet,并确保每次都选择一个新图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多