I have an ImageView in which I want to set an image depending upon a random value
What I know is I can set an image like this
public void onRollClick(View view) {
String[] images={"dice1.png","dice2.png","dice3.png","dice4.png","dice5.png","dice6.png"};
int diceValue=new Random().nextInt(6);
ImageView diceImage= (ImageView) findViewById(R.id.imageView);
diceImage.setImageResource(R.drawable.dice5);
}
where onClick method is called on a Button click. All images are in drawable directory. Currently, I always set image dice5.png. How could I instead set, images[diceValue] image?
Note: I am using API 22
You can simply store the ID of your resources!
public void onRollClick(View view) {
int[] images= {R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6};
int diceValue=new Random().nextInt(6);
ImageView diceImage= (ImageView) findViewById(R.id.imageView);
diceImage.setImageResource(images[diceValue]);
}
I'm just suggesting to use a image loading library like Picasso right away. This makes the performance a lot better and is super simple to implement. You can get the library here: http://square.github.io/picasso/ and this would be your code to go with:
public void onRollClick(View view) {
int[] images= {R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6};
int diceValue=new Random().nextInt(6);
ImageView diceImage= (ImageView) findViewById(R.id.imageView);
Picasso.with(this).load(images[diceValue]).into(diceImage);
}
Edit: You should definitely bump up your API version ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With