我正在使用Android Studio制作通用应用;我想从我的阵列中显示4个随机图像,但不知道如何防止图像重复。
public class answerScreen extends AppCompatActivity {
ImageView imageView, imageView2, imageView3, imageView4;
Random r;
Integer[] images = {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer_screen);
imageView = (ImageView) findViewById(R.id.imageView);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView3 = (ImageView) findViewById(R.id.imageView3);
imageView4 = (ImageView) findViewById(R.id.imageView4);
r = new Random();
//diplay random image
imageView.setImageResource(images[r.nextInt(images.length)]);
imageView2.setImageResource(images[r.nextInt(images.length)]);
imageView3.setImageResource(images[r.nextInt(images.length)]);
imageView4.setImageResource(images[r.nextInt(images.length)]);
}
}
您可以在[0,images.length)
范围内生成4个随机整数,并将它们存储在数组中,例如:
Random r = new Random();
int randInts [] = r.ints(0, images.length).distinct().limit(4).toArray();
并使用该数组设置图像资源:
imageView.setImageResource(images[randInts[0]]);
imageView2.setImageResource(images[randInts[1]]);
imageView3.setImageResource(images[randInts[2]]);
imageView4.setImageResource(images[randInts[3]]);
将数组改组然后获取前四个项目是执行此操作的一种简单方法。一个简单的例子:
Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
List<Integer> intList = Arrays.asList(intArray);
Collections.shuffle(intList);
intList.toArray(intArray);
System.out.println(Arrays.toString(intArray));