I'm making a generic app using Android Studio; I want to display 4 random images from my array but don't know how prevent an image repeating.
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)]);
}
}
You could generate 4 random ints in range [0,images.length)
and store them in an array like:
Random r = new Random();
int randInts [] = r.ints(0, images.length).distinct().limit(4).toArray();
and use that array to set image resources:
imageView.setImageResource(images[randInts[0]]);
imageView2.setImageResource(images[randInts[1]]);
imageView3.setImageResource(images[randInts[2]]);
imageView4.setImageResource(images[randInts[3]]);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments