preface

Since Android5.0, the Drawable mechanism has been changed. Apps share the same resource, which saves memory, but can cause unexpected problems if you are not careful.

knowledge

Drawable Memory share

Pay attention to the point

If multiple Drawable loads the same image in App, the same memory will be shared.

Drawable. SetAlpha method, due to shared memory, will affect the transparency of the corresponding resources throughout the App.

· · · · · ·

Such as: control

textview.getBackground().setAlpha(0);
Copy the code

The background color of the original TextView is white, then after the transparency is set to 0, the white background color of the entire App will receive the notification of. SetAlpha (0), and all background colors will become transparent.

Solutions:

/** * 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. * * Calling this method on a mutable Drawable will have no effect. * *@return This drawable.
 * @see ConstantState
 * @see #getConstantState()
 */
public @NonNull Drawable mutate(a) {
    return this;
}
Copy the code

Comment meaning: make this drawable mutable. This action cannot be undone. Guarantee that mutable drawable objects do not share their state with any other drawable objects. This feature is especially useful when you need to modify the properties of drawable objects loaded from resources. By default, all instances of drawable loaded from the same resource have the same state; If you change the state of one instance, all other instances receive the same changes.

How to use: Calling this method on a mutable Drawable will not cause its state to be shared.

 textview.getBackground().mutate().setAlpha(0);
Copy the code