Search code examples
javaandroidbackground-imagealpha

android: getBackground.setAlpha() changes alpha of all activities with same background-image


For example, if I add the following line to my 2nd activity, the alpha value for the background image will also change in my 1st activity, because I used the same image.

findViewById(R.id.main).getBackground().setAlpha(100);

But I don't want that. The two activities should have different alpha values, but still have the same drawable as background image. How can I achieve this?


Solution

  • You should call mutate() to create a separate instance before setting the alpha. As per the documentation:

    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.