3

I have 110 images, all labeled 1, 2, 3, etc. I'd like to be able to set it up so that I can generate a random number and then display that image on the screen. The display part is fine, but I'm not sure about the array.

So far, all I've seen are arrays that require manual setup - typing in each name in XML. For 10 or 15 images, that's not bad. For 110, or thousands (in the future, hopefully), it's pretty inefficient. Is there a way to display an image based on its title, not resource ID? Ideally, I'd like to be able to title my images "ENG_1" and "SPA_1" to show different images for different languages, so it'd be nice to have it based on a String instead of an int, for searchability (if that's a word) and ease of access.

So, how would I start that?

1 Answer 1

3

Yes, there's a method Resources.getIdentifier(String name, String defType, String defPackage). You can use in the following way:

Resources resources = getResources();
int id = resources.getIdentifier("ENG_1", "drawable", getPackageName());
Drawable drawable = resources.getDrawable(id);
Sign up to request clarification or add additional context in comments.

2 Comments

Should we use this method? I see many people said it'll make application slow.
You shouldn't if you can avoid it. But if you have no choice, then it seems to be the only solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.