Reputation: 131
iv.setImageResource(R.drawable.icon);
this line is working good for me
can I pass a variable value instead of icon like if i have 10 images in drawable and i want to decide on runtime which image to show can i pass the value through a variable and work it like
String variableValue = imageName;
iv.setImageResource(R.drawable.variableValue);
Upvotes: 12
Views: 17533
Reputation: 6949
Resources.getIdentifier() can solve your problem.
String variableValue = imageName;
iv.setImageResource(getResources().getIdentifier(variableValue, "drawable", getPackageName()));
Upvotes: 22
Reputation: 19220
No, it won't work that way.
In your first line icon
is a generated static final
member of the static final class R.drawable
so trying to concatenate it up like it was a String
would give you a compiler error.
But you could try using
iv.setImageURI(uri);
where uri
is the URI to your image, so you can use a string value here.
Also, according to the api documentation, it would be a better solution to use setImageBitmap
: you should consider it based on your resources.
APIDocs:
public void setImageURI (Uri uri)
Since: API Level 1
Sets the content of this ImageView to the specified Uri.
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(Drawable) or setImageBitmap(Bitmap) and BitmapFactory instead.
Parameters
uri
The Uri of an image
Upvotes: 0
Reputation: 52247
You could use an array to define your drawables:
int[] images = new int[2];
images[0] = R.drawables.image1;
images[1] = R.drawables.image2;
And then you can use this array to set a image at runtime:
lv.setImageResource(images[i]);
Where is is in this case either 0 to point to the first image or 1 to point to the second image of the array.
Upvotes: 5