Reputation: 1314
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 String
s 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
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
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
Reputation: 7038
The Reflection API is working on Android. It's something that all Java Developer should learn.
Upvotes: 0
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
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