androidxmlshapedrawable

problems of changing the color of shapedrawable


I use this xml in two places, and i changed the color of one of the two programmatically, i found out that the other one's color also changed, why can this be?

<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@color/blue" />
  <corners android:radius="2dp" />
</shape>

Solution

  • Use Drawable.mutate().

    Even though every time you load a Drawable from resources you receive a new instance, for performance reasons, they all share ConstantState. This ConstantState usually holds all the properties that can be declared for a Drawable, its color in your example.

    Therefore if you modify the color of one of the Drawables the change gets reflected in its ConstantState and the change is visible for all the other instances which share the same ConstantState.

    As the documentation of Drawable.mutate() states:

    Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification.

    You can check this great post by Romain Guy for more details.