Search code examples
androidrippledrawableandroid-shapeandroid-shapedrawable

Android change color of shape Instance


I have three buttons with same ripple shape.

when I enter activity I change color of single buttons shape.

RippleDrawable bg = (RippleDrawable) button.getBackground(); GradientDrawable gradient = (GradientDrawable) bg.findDrawableByLayerId(R.id.ripple_color); gradient.setColor(Color.Black);

but when I reenter activity all buttons have this new color. How to change only this instance of shape instead of modifying shape itself


Solution

  • From the Drawable documentation:

    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.

    So your problem is here:

    GradientDrawable gradient = (GradientDrawable) bg.findDrawableByLayerId(R.id.ripple_color);
    gradient.setColor(Color.Black);
    

    To avoid the issue mentioned in the documentation, simply call mutate() on the drawable before changing its state.

    GradientDrawable gradient =
            (GradientDrawable) bg.findDrawableByLayerId(R.id.ripple_color).mutate();
    gradient.setColor(Color.Black);