Registered User
Registered User

Reputation: 2299

How do I set image decided at runtime in ImageView?

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

Upvotes: 3

Views: 827

Answers (4)

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 ;)

Upvotes: 1

Shabbir Dhangot
Shabbir Dhangot

Reputation: 9121

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]);
}

Instead of string array create array of int drawables. so you can directly use them.

I have edited your function.

Upvotes: 0

pdegand59
pdegand59

Reputation: 13029

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]);
}

Upvotes: 5

Related Questions