2 myq 26 myq_26 于 2012.10.11 11:38 提问

在ImageView中让图像随机出现

在imageview中有9个图像视图。我想让这几个图像在imageview中随机显示。我想实现点击刷新按钮,图像就会随机分配。但是每次点击后总是在俩个或三个imageview中重复出现相同的图片。程序中哪里有问题呢?

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

2个回答

hxn_217
hxn_217   2012.10.11 13:31
已采纳

用这段代码,容易实现。

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;
                 }
               }
            }
            }
        }
znl_12
znl_12   2012.10.11 16:57
List<int> list = Arrays.asList(images);
   Collections.shuffle(list);

int i=0;

for (int picture: list) {
    ImageView iv = (ImageView)findViewById(imageViews[i]);
    iv.setImageResource(picture);
    i++;
}
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);
        }
    }
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!