同一个ImageView setColorFilter后,再set任何图片都会自带滤镜效果。(有点像java对象的引用)
解决办法:
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher).mutate(); drawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); imageView.setImageDrawable(drawable);
//在Drawable源码中,mutate方法只是返回了他自身。
//而在drawable子类对该方法重写。比如BitmapDrawable@Override public Drawable mutate() { if (!mMutated && super.mutate() == this) { mBitmapState = new BitmapState(mBitmapState); mMutated = true; } return this; }
参考文章:https://www.jianshu.com/p/d11892bbe055
另外一个方法就是不改drawable本身的颜色,直接改控件的颜色
这样写表示先改drawable,然后被图片控件引用。但是在某些特殊情况下,会不起效(我遇到的具体场景是,当drawable变更时,对drawable着色后再被图片引用,图片实际没有被着色)
Drawable drawable = imgs.get(i);
drawable.setColorFilter(R.color.aaa,PorterDuff.Mode.SRC_ATOP);
iv.setImageDrawable(drawable);
对策就是不改drawable,直接对iv控件进行着色调用,这样页面就能把着色刷新出来。
Drawable drawable = imgs.get(i);
iv.setImageDrawable(drawable);
iv.setColorFilter(R.color.aaa,PorterDuff.Mode.SRC_ATOP);
在代码里不能直接使用资源文件的颜色
//不起作用
holder.icon.setColorFilter(R.color.icon_disable);
//正常
holder.icon.setColorFilter(ContextCompat.getColor(getContext(), R.color.icon_disable));
/**
原因
getColor returns the actual AARRGGBB color value.
R.color.Black is an id that holds a color, which may or may not be black.
One is the actual value, one is a reference to the color.
*/