• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Referencing Resource Via String

safibaba

Newbie
I was just wondering if there is any way to reference a resource using a string.

Say you had 10 images in your drawable folder called 'img1' 'img2' 'img3' etc......

PHP:
int imgNum = 2;
String imgName = "img"+imgNum;
Drawable d = (Drawable) getResources().getDrawable(R.drawable.imgName);

Is there any way of doing this? Or will I just have to use if statements to work out which image to use?
 
Hi,

It might be overkill, but if you want something that will scale up to handle lots of resources then you could use Java reflection.

I describe a solution in another thread:

http://androidforums.com/android-de...lements-res-raw-folder-one-shot-run-time.html

You'd have to adapt the code a little. Instead of:

Code:
Field fields[] = R.raw.class.getDeclaredFields() ;

You'd have to use:

Code:
Field fields[] = R.raw.drawable.getDeclaredFields() ;

If you're familiar with Java reflection then hopefully that other thread will give you an idea of how to achieve what you want.

I can explain further if you like. Just ask.

Regards,

Mark
 
To answer your first question: no, I don't know a way to reference your drawables by a String.

To answer your second question: I use Maps to handle problems like yours where I know there are going to be multiple statically paired items.

For example, I might declare the global variable:
Code:
public static final String PREFIX = "img";
public static final Map mImageMap = new HashMap<String, Drawable>();
...then, in onCreate I'd pay the one time setup fee by putting:
Code:
if (mImageMap.size() == 0) {
   mImageMap.put(PREFIX + "1", getResources().getDrawable(R.drawable.img1));
   mImageMap.put(PREFIX + "2", getResources().getDrawable(R.drawable.img2));
   mImageMap.put(PREFIX + "3", getResources().getDrawable(R.drawable.img3));
}
and then finally when I want to reference the value, I would do something like:
Code:
int exampleInput = 2;
Drawable d = mImageMap.get(PREFIX + exampleInput);
 
Ahh - hashmap - that's a great idea!

I'm so used to working a a language where this is possible, I didn't even think of making a dictionary / hash.

Thanks Boogs. I actually just wrote a factory method to return the relevant image, since there were only three, but I will need to do one with much more images soon, so this will be a great solution, and much easier to maintain.

Cheers:):)
 
Back
Top Bottom