Android-不可描述的小知识-Drawable的内存共享

前言

​ 踩坑记录,从Android5.0以后,Drawable的机制改了,App共享同一资源,这样节省内存,但是不注意则会导致意想不到的问题。

知识点

Drawable 内存共享

注意点

在App中多个Drawable加载同一张图片,将共享同一块内存。

Drawable.setAlpha 方法中,由于共享内存,会影响整个App的相应资源的透明度。

······

如:控件

textview.getBackground().setAlpha(0);
复制代码

原textview的背景色为白色,则设置透明度为0后,整个App的白色背景色接收.setAlpha(0)通知,全部背景色变透明。

解决方法:

/**
 * 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() {
    return this;
}
复制代码

注释的意思:使此可绘制可变。 此操作不能撤消。 保证可变的可绘制对象不会与其他任何可绘制对象共享其状态。当您需要修改从资源加载的可绘制对象的属性时,此功能特别有用。 默认情况下,从同一资源加载的所有drawable实例均具有相同的状态; 如果您修改一个实例的状态,则所有其他实例将收到相同的修改。

使用方法:在可变的Drawable上调用此方法将不会导致共享其状态。

 textview.getBackground().mutate().setAlpha(0);
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享