Roshnal
Roshnal

Reputation: 1314

Create a variable name from a String?

I'm making an Android application and it's got a lot of images (about 200). And I want to show the specific image according to what the user selects.

The selections are in the form of Strings such as "USD", "AUD", "LKR", etc. And the images are in the form "usd.png", "aud.png", "lkr.png" and so on. I have put the images in the /res/drawable-mdpi folder and I usually access them like R.drawable.usd and so on.

But in this case its [obviously] hard to do that (for 200+ icons). So is there anyway I can obtain the specific image according to user selection? For example, when user selects "USD", I want to obtain the image named "usd.png". Any help?

Thanks in advance.

Upvotes: 1

Views: 1308

Answers (5)

Philip Sheard
Philip Sheard

Reputation: 5815

If you can construct the name of the resource, you can call getResources().getIdentifier() to get the id, then you can take it from there.

Upvotes: 2

phtrivier
phtrivier

Reputation: 13361

Could you use a combination of Resources.getIdentifier and Resources.getDrawable ?

http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)

http://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int)

Upvotes: 2

Nicolas Zozol
Nicolas Zozol

Reputation: 7038

The Reflection API is working on Android. It's something that all Java Developer should learn.

Upvotes: 0

Tim Büthe
Tim Büthe

Reputation: 63734

I'm not sure if Android has methods to access the resources by name, however you can always use reflection to do such things in Java:

R.drawable.getClass().getField("nameGoesHere").get(null)  

Upvotes: 0

Óscar López
Óscar López

Reputation: 235984

Use a Map for storing the String as a key, with the image name as a value. For example:

Map<String, String> images = new HashMap<String, String>();
images.put("USD", "usd.png");        // store the reference
String usdImage = images.get("USD"); // retrieve the reference

Upvotes: 0

Related Questions