Issue
So I have a db that stores string values of a path to an image. My goal is to show the corresponding image using a string that matches the name of the image, but I'm having a hard go of it.
Movie currentMovie = values.get(position);
ImageView image = (ImageView)itemView.findViewById(R.id.movieThumbnail);
String path = "@drawable/" + currentMovie.getThumb();
int imageResource = getResources().getIdentifier(path, "drawable", getPackageName());
Drawable thumbnail = getResources().getDrawable(imageResource);
image.setImageDrawable(thumbnail);
unfortunately the imageResource is always 0 and I get a source not found. The currentMovie,getThumb() returns the text "test.png", and under res\drawable-hdpi is the test.png file. How can I reference this image? do I need an xml file?
Solution
Use this simple function to return a drawable when you only have the image name. You do not need to include the full path to the drawable folder or the image filename extension.
The Drawable will be loaded from whichever density folder is in use by the Context
you pass in.
Drawable getMyDrawable(Context c,String ImageName) {
return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}
In your example, from your activity you would simply call :
image.setImageDrawable(getMyDrawable(this,"test"));
Answered By - Kuffs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.