Roger That
Roger That

Reputation: 95

Showing an image without specifying src in xml

I want to show an image, depending on the value of the int imgch

This is in my onCreate:

    ImageView image = (ImageView)findViewById(R.id.gimage);
    Resources res = getResources();
    Drawable gameImage = res.getDrawable(images[imgch]); 

And this in my XML:

     <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/gimage" />

How do I get it to show the correct image in the activity?

Upvotes: 1

Views: 530

Answers (4)

Vladislav Kan
Vladislav Kan

Reputation: 354

use

Resources resources = getResources();
image.setImageDrawable(resources.getDrawable(R.drawable.myfirstimage));

Upvotes: 0

BredeBS
BredeBS

Reputation: 198

Create an Array

int[] images;

on

protected void onCreate(Bundle savedInstanceState) {

add this

images = new int[3];
images[0] = R.drawable.first_image;
images[1] = R.drawable.second_image;
images[2] = R.drawable.third_image;

and then your code (where imgch is an integer)

...
Drawable gameImage = res.getDrawable(images[imgch]); 
...

Upvotes: 0

BredeBS
BredeBS

Reputation: 198

Yes, but with java-side code

ImageView img = (ImageView) findViewById(R.id.gimage);
img.setImageDrawable(getDrawable(R.drawable.my_image_name));

If you wanna load from an remote url you may be use this

https://github.com/nostra13/Android-Universal-Image-Loader

Upvotes: 2

michal.z
michal.z

Reputation: 2075

Check this ImageView#setImageDrawable. So you should have image.setImageDrawable(gameImage)

Upvotes: 1

Related Questions