Search code examples
androiddrawablelayerresource-id

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


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!


Solution

  • There is no such thing as an ID for a Drawable created at runtime. Those IDs refer to int fields in the R class, automatically created from the xml files.

    Since the LayerDrawable constructor requires just a Drawable array, you can provide those Drawables made from any method. An example, would be the static method Drawable.createFromStream(InputStream is, String srcName).

    http://developer.android.com/reference/android/graphics/drawable/Drawable.html#createFromStream%28java.io.InputStream,%20java.lang.String%29