我正在使用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)]);
}
}
});
我不想重复,一个图像仅适用于一个imageview ..
解决方法:
使用blessenm的帖子,我写了一个你需要的类似代码.检查这是否对您有所帮助.
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;
}
}
}
}
});