views:

46

answers:

3

I want to load bitmaps into ImageViews in Android, but I don't want to use the R.drawable syntax because I have a lot of images with a standard naming convention so it's much easier to get the image with some logic. For example, all my images are named:

img1.png img2.png img3.png

So if a user selects a value, let's say x, I show "img" + x + ".png" in the ImageView. Looks like Bitmap.decodeFile is what I need, but I need to know the syntax of how to get to my drawables folder since that's where the images are. Or if there's perhaps a better way.

I realize I could do this with a switch statement instead of concatenating the image name but that would be a lot of lines since I have so many images.

+1  A: 

One alternative is to use reflection to load images from R. You can looking static variables by string name. Keep in mind that reflection can be slow though. If you are going to be loading the same image multiple times, you might want to keep a cache of name -> R id.

Edit: You can also access them by URI. See referring to android resources using uris.

Mayra
That sounds like it could work but I would imagine referencing the file by its path and name would be simpler.
CYAD
See edit.......
Mayra
A: 

The R.drawable value is a number by itself. You just need to use the first image id and add a fixed value to find the right image. For example:

R.drawable.image1 = 1234; R.drawable.image2 = 1235; etc.

So to get image 2 I would to R.drawable.image1 + 1.

Every time the R.java file is regenerated the numbers may change but the sequence will be the same. If you don't want to depend in this then you will have to look at the "assets" folder.

Eli
A: 

Looks like I've found a solution. The real problem is that I generate the resource names at runtime, but I can get the resource id like this: getResources().getIdentifier("string1" + string2, "id", "com.company.package")

I can then pass that value to setImageResource or any other method that accepts a resource id.

CYAD