公司项目有一个需求,图标从网络下载,根据不同的状态设置不同的透明度,于是想当然地这么写:
Drawable drawable = imageView.getDrawable();
drawable.setAlpha(alpha);
结果有些图标设置成功了,有些失败。调试发现,成功的都是SquaringDrawable,而失败的都是BitmapDrawable。
进一步调试发现,SquaringDrawable是Glide框架的,BitmapDrawable是系统的。查找资料得知,BitmapDrawable调用setAlpha不是直接调用其自身的Paint,而是通过一个mBitmapState来实现,这个mBitmapState是底层共享的,至于怎么修改,不得而知。不过我们可以通过调用Drawable的mutate()方法来阻断这种共享性,这是BitmapDrawable的mutate()方法源码:
@Overridepublic Drawable mutate() {if (!mMutated && super.mutate() == this) {mBitmapState = new BitmapState(mBitmapState);mMutated = true;}return this;}
解决方案:
结合Glide代码,我是这么写的:
Glide.with(mContext).load(url).asBitmap().error(R.drawable.ic_app_load).placeholder(R.drawable.ic_app_load).dontAnimate().into(new SimpleTarget<Bitmap>() {@Overridepublic void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);drawable.mutate();imageView.setImageDrawable(drawable);}});
这里,我在源头上指定了imageView的drawable为BitmapDrawable,并调用mutate()方法,而不是由glide自动为我们指定drawable类型。注意,当imageView设置drawable后,再调用mutate()方法阻断已经晚了。