Android – Load drawables by name from resources

Sometimes you need to load some images knowing only their names. For example, in a game you have 100 images of soldiers, everyone looking different than the other. Obviously, loading them from resources is not such a good idea, imagine 100 lines of code like this: getDrawable(R.drawable.soldier1). Then you will want to use assets, because you could then do it like this:

Drawable soldiers[] = new Drawable[100];
for(int i = 0; i < 100; i++)
{
	soldiers[i] = Drawable.createFromStream(getAssets().open("soldier" + i + ".png"), null);
}

The only problem with this is that your images will have the same resolution no matter what dpi the phone has and this will result either in poor performance (if the images have high resolution and run on low dpi phones) or in blurry images (if the images have a low resolution and run on high dpi phones). This means you have to go back to using resources and this is how you will load the drawables from resources:

Drawable soldiers[] = new Drawable[100];
for(int i = 0; i < 100; i++)
{
    int soldierResourceID = context.getResources().getIdentifier("soldier" + i, "drawable",  context.getPackageName());
    soldiers[i] = getResources().getDrawable(soldierResourceID);
}

Leave a Reply

You must be logged in to post a comment.