14

say I want to dynamically load an image file in R.drawable.* based on the value of a string

Is there a way to do this? It seems like I need to statically refer to anything in R.

Rolf ツ
  • 8,611
  • 6
  • 47
  • 72
RandomUser
  • 4,140
  • 17
  • 58
  • 94

3 Answers3

22

Have you declared the id for the image in XML file? If you did, you can use the following method:

Let's say you have picture.png in your res/drawable folder.

In your activity, you can set your image resource in the main.xml file

<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>

In FirstActivity

//to retrieve image using id set in xml.
String imageString = "imageId"
int resID = getResources().getIdentifier(imageString , "id", "package.name");
ImageView image = (ImageView) findViewById(resID);

imageString is the dynamic name. After which you can get the identifier of the dynamic resource.

Another method, you can do this:

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );

You will be able to reference your image resource and set your ImageView to it.

Community
  • 1
  • 1
newbie
  • 958
  • 4
  • 13
  • 25
  • Thanks, for this method to work I would need to declare the image in the AndroidManifest.xml file, or is there another file? I wasn't able to find good info on this, but mabey im searching for the wrong thing – RandomUser Oct 30 '11 at 00:44
  • I have edited my example. Added 2 ways of retrieving the images. One is dynamically through the id in XML used for your activity. The other dynamically from the `res/drawable` folder. You do not need to declare images in AndroidManifest.xml. – newbie Oct 30 '11 at 07:13
  • need to rephrase.. One method is to dynamically retrieve the image. The other is to set the image. Not sure which one are you trying to do – newbie Oct 30 '11 at 07:20
  • Great response, really appreciate it! Thanks again for the help! – RandomUser Oct 30 '11 at 20:33
9
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);

Try this. This should work.

Namita
  • 49
  • 9
Yashwanth Kumar
  • 28,931
  • 15
  • 65
  • 69
1
Class res = R.string.class;
Field field = res.getField("x" + pos);
headerId = field.getInt(null);
header.setText(headerId);

this works with drawables as well, just edit the string. the header part is not required, it's just an example pulled from something I wrote a while ago.

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66