Android: Cloning a drawable in order to make a StateListDrawable with filters Android: Cloning a drawable in order to make a StateListDrawable with filters android android

Android: Cloning a drawable in order to make a StateListDrawable with filters


Try the following:

Drawable clone = drawable.getConstantState().newDrawable();


If you apply a filter / etc to a drawable created with getConstantState().newDrawable() then all instances of that drawable will be changed as well, since drawables use the constantState as a cache!

So if you color a circle using a color filter and a newDrawable(), you will change the color of all the circles.

If you want to make this drawable updatable without affecting other instances then, then you must mutate that existing constant state.

// To make a drawable use a separate constant statedrawable.mutate()

For a good explanation see:

http://www.curious-creature.org/2009/05/02/drawable-mutations/

http://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()


This is what works for me.

Drawable clone = drawable.getConstantState().newDrawable().mutate();