Search code examples
androidxmlkotlinreset

Invalidate GradientDrawable


I have the following xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

    <solid android:color="@color/color_primary_dark" />
    <size android:width="25dp" android:height="25dp" />
    <stroke android:width="1dp" android:color="@android:color/white" />

</shape>

And at some point in my application I change the color of this shape like this:

// priority_button has this shape as is src
(priority_button.drawable as GradientDrawable).setColor(ContextCompat.getColor(this, android.R.color.holo_orange_light))

The problem is: if I destroy the activity and then re-open the same activity, this shape stays with the last color that I set (in this case android.R.color.holo_orange_light) and I want to that shape reset to the same color that is defined in the xml (R.color.color_primary_dark).

Since I am setting the color programmatically I think that I am changing the xml itself and when the activity is re-opened, and the views are draw, it gets the xml that I set another color.

Is any way to reset the xml values or something like this?


Solution

  • Try invoking mutate() on the drawable before changing its color.

    As per setColor(int argb) documentation it states that:

    changing color will affect all instances of a drawable loaded from a resource. It is recommended to invoke mutate() before changing the color.

    So maybe this affects you as well.