原文来自Android SDK文档中的 resources/articles/drawable-mutations.html
在Android中有大量的图片加载,Android性能优化其加载过程,也就是说在每一个加载的drawable添加一个共享状态。
虽然共享状态能够节约很多内存,但是同样也会带来对图片修改带来一些麻烦。
Android在图片中添加了一个共享的状态图.如下:
从代码上来看
getDrawable().mutate();
/**
* 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()
*/
/ **
*将此绘制可变的。此操作无法逆转。一个可变
*提拉是保证不与任何其他可拉伸共享其状态。
*当你需要修改的可绘性质,这是特别有用
*从资源加载。默认情况下,所有的可绘实例从装
*相同的资源共享共同的状态;如果您修改一个状态
*实例中,所有的其他实例将接收相同的修饰。
*
*调用一个可变的可绘制这种方法不会有任何效果。
*
返回:此绘制。
*@see ConstantState
*@see#getConstantState()
* /
也就是说,如果你多个页面都共用了这个图片,那么你可以通过这个mutate()方法获得一个与这个相同的图片,然后可以对此处进行处理。
例如:
在listview中如果运用了评分的控件;(共用一张图的情况)
没使用共享状态
- Drawable star = context.getResources().getDrawable(R.drawable.star);
- if (book.isFavorite()) {
- star.setAlpha(255); // opaque
- } else {
- star.setAlpha(70); // translucent
- }
使用了共享状态:
- Drawable star = context.getResources().getDrawable(R.drawable.star);
- if (book.isFavorite()) {
- star.mutate().setAlpha(255); // opaque
- } else {
- star. mutate().setAlpha(70); // translucent
- }