How to get Android resource ID from dynamically-created (in Java) layer-list / LayerDrawable?

scary alien picture scary alien · Apr 12, 2011 · Viewed 17.5k times · Source

The "solution #2 (dynamic)" in this question/answer post:

overlay two images in android to set an imageview

is very close to what I want to do, which is to dynamically create a layer-list (for a status bar notification icon, I want to build-up my icon in layers), but the icon assignment in the notification API requires a resource ID (which I want to call from a service).

I cannot figure-out how to build a dynamically build a layer-list without building hundreds of layer-list .xml files (for the various combinations of icons that I would like to be able to display). Daniel's "solution #1" works wonderfully for the static .xml files, but I'm looking for a more elegant, dynamic solution.

In the above post, the code snippet:

  Resources r = getResources();

  Drawable[] layers = new Drawable[2]; 

  layers[0] = r.getDrawable(R.drawable.t);

  layers[1] = r.getDrawable(R.drawable.tt);

  LayerDrawable layerDrawable = new LayerDrawable(layers);

appears to be what I want, but I don't know or understand how to "assign" the new layerDrawable to my notification icon (which takes a resource ID).

Thanks to all...stackoverflow is a wonderful resource!

Answer

hasanghaforian picture hasanghaforian · May 24, 2012

Use "getIdentifier" to get it.Suppose that I have a file bug.png in the "/res/drawable/", so i get its ResourceID with the following code:

int resID = getResources().getIdentifier("org.anddev.android.testproject:drawable/bug", null, null);

// or

int resID = getResources().getIdentifier("bug", "drawable", "org.anddev.android.testproject");      

reference:
anddev.org