How to change a layer-list drawable?

Question: How do I programmatically reference one of the drawables in the layer-list so I can change it to a different drawable?

Here’s what I would try:

Step #1: Put android:id attributes on the <item> elements as illustrated in the documentation

Step #2: Cast the getDrawable() result to a LayerDrawable

Step #3: Call mutate() if you do not want to affect anyone else using the Drawable (may be optional)

Step #4: Call setDrawableByLayerId() to set/replace a Drawable for a given layer ID

Leave a Comment