Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android -- Using Array of Image Resources

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?

like image 632
camdroid Avatar asked May 29 '26 23:05

camdroid


1 Answers

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);
like image 71
Michael Avatar answered Jun 01 '26 12:06

Michael