I am storing my project related images in drawable folder. Also I am storing the image names in string variable and dynamically I am trying to set those images to the imageview. But the image is not displaying. Please help me in this regard.
My Code:
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
In the above code "imagename" is the string variable which contains the image name.
Thanks in advance
Here is the best way that works in every phone at today. Most of those answer are deprecated or need an API >= 19 or 22. You can use the fragment code or the activity code depends what you need.
Fragment
Activity
Cheers!
First of let's your image name is myimage. So what you have to do is that go to Drawable and save the image name myimage.
Now assume you know only image name and you need to access it. Use below snippet to access it,
what you did is correct , ensure you saved image name you are going to use inside coding.
In addition to it you should ensure that there is no empty spaces and case sensitives
Try this Dynamic code
In above code you will need Image-file-Name and Image-View object which both you are having.
See below code this is working for me
As of API 22,
getResources().getDrawable()
is deprecated (see also Android getResources().getDrawable() deprecated API 22). Here is a new way to set the image resource dynamically:Here i am setting the
frnd_inactive
image fromdrawable
to the image