Android r.drawable dynamic name

Android-r-drawable-dynamic-name-featured.jpg

Dynamically Locating Assets in Android
Normally, when locating assets (drawables, strings, whoever else) in code you apply the instantly produced R.java to do this. However, I lately authored a reference application in which the items inside a ListView includes a different icon alongside it. The information for those this really is saved in JSON being an resource, which resulted in there is not a way that i can link my data to R.java.

Still, I desired a way to get hold of the Drawable by name, therefore i first switched to Assets.getIdentifier(). This process will the job well of locating the resource id of whatever you desire, in almost any package:

Assets r = getResources()
int drawableId = r.getIdentifier(“drawableName”, “drawable”, “com.mypackage.myapp”)

This really is all fine and dandy, but: getIdentifier() is really a general oral appliance consequently, slow. Running through 10,000 iterations, it required about 3200 ms on my small G1. Also, it takes that you simply pass around a Context (or perhaps a Assets) wherever you should utilize getIdentifier() that is an annoyance and appears unnecessary given that you could access R.java all right normally in code.

The greater solution – as lengthy when you are locating data out of your application’s own R.java – is by using reflection.

try Area area = res.getField(“drawableName”)
int drawableId = area.getInt(null)

catch (Exception e) to obtain drawable id.”, e)

In testing, the 2nd technique is about 5x faster than getIdentifier(). Not just that, however it means it’s not necessary to pass a Assets object around for doing things. Clearly this can’t be used if you are being able to access assets outdoors of the application’s permissions and you will have to depend on getIdentifier() then.

One further note – simply connecting to R.java is much faster than either of those two techniques, so only select from these if you want to connect to resource identifiers dynamically by name.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>