I have 54 images I need to show only 8, but there has to be a random selection and they can not be repeated, I'm programming on the Android Studio platform.
I use this code it works quietly, it shows the results in 8 ImagemView
, More .... it repeats the results of the image;
insira o código aqui
public void Button2(View view) {
final int[] imageViews = {
R.id.imageView, R.id.imageView4, R.id.imageView7,
R.id.imageView2, R.id.imageView5, R.id.imageView8,
R.id.imageView3, R.id.imageView6,};
final int[] images = {
R.drawable.1,
R.drawable.2,
R.drawable.3,
R.drawable.4,
...... vai até o 54
};
final Button shuffle = (Button) findViewById(R.id.Button2);
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)]);
}
}
});
}
insira o código aqui
I used this Code below to solve the problem.
};
final Button shuffle = (Button) findViewById(R.id.Button4);
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 < 8; i++)
{
while(true)
{
Integer next = rng.nextInt(54) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
break;
}
}
}
}
});}}
insira o código aqui
Source: link