2014-05-10 28 views
0

我有幾個圖像視圖和幾個圖像添加到佈局,我隨機添加它們,我需要確保兩個圖像視圖不包含相同的圖像...這裏是我的for循環動態添加圖像到圖像視圖。如何查看這樣的圖像不包含相同的圖像

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

     for(int v : imageViews) { 

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

     } 

我發現了一個辦法做到這一點,我會添加editted代碼:

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

回答

3

最簡單的方法是將有圖像的列表<>而不是一個數組,在循環開始之前調用Collections.shuffle(images, random)。這樣,只要按順序選擇圖像,就可以保證不重複。

這將是一個非常好的解決方案,尤其是如果圖像採集不是非常大(否則你可能會洗牌一個非常大的列表只選擇它的一小部分)。

如果集合很大,那麼您可以保留一個HashSet的位置已經選擇,並確保每次都選擇一個新的圖像。

相關問題