Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the image from drawable dynamically in android?

Tags:

android

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

like image 452
hemanth kumar Avatar asked Jul 31 '12 10:07

hemanth kumar


People also ask

How to set image from drawable android?

To use an image resource, add your file to the res/drawable/ directory of your project. Once in your project, you can reference the image resource from your code or your XML layout. Either way, it's referred to using a resource ID, which is the file name without the file type extension. For example, refer to my_image.


2 Answers

Try this:

String uri = "@drawable/myresource";  // where myresource (without the extension) is the file  int imageResource = getResources().getIdentifier(uri, null, getPackageName());  imageview= (ImageView)findViewById(R.id.imageView); Drawable res = getResources().getDrawable(imageResource); imageView.setImageDrawable(res); 
like image 154
rfsbraz Avatar answered Sep 21 '22 14:09

rfsbraz


Here i am setting the frnd_inactive image from drawable to the image

 imageview= (ImageView)findViewById(R.id.imageView);  imageview.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive)); 
like image 31
Ram kiran Pachigolla Avatar answered Sep 20 '22 14:09

Ram kiran Pachigolla