方法一:setColorFilter(存在向后兼容问题)
如果给多个View设置了同一个Drawable资源,即使只给一个Drawable设置了着色,其余的也都会被着色。这是因为 Android 为了优化系统性能,资源Drawable只有一份拷贝,修改了一个,等于将所有的都修改了。
<span style="font-size:14px;"> Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ic_launcher);
if (i % 2 == 0) {
drawable.setColorFilter(mContext.getResources().getColor(android.R.color.holo_blue_light), PorterDuff.Mode.SRC_IN);
} else {
drawable.clearColorFilter(); // 等效于drawable.setColorFilter(null);
}
viewHolder.icon.setBackground(drawable);</span>
这里可以用Drawable提供的mutate()方法
来打破这种共享状态,调用mutate()方法
不会拷贝内存中公共的Bitmap,只会拷贝一份Bitmap的状态值,这样便达到了我们想要的效果了。具体可以参考这篇文章:Drawable mutations
Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ic_launcher).mutate();
if (i % 2 == 0) {
drawable.setColorFilter(mContext.getResources().getColor(android.R.color.holo_blue_light), PorterDuff.Mode.SRC_IN);
} else {
drawable.clearColorFilter(); // 等效于drawable.setColorFilter(null);
}
viewHolder.icon.setBackground(drawable);
Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ic_launcher);
if (i % 2 == 0) {
viewHolder.icon.setBackgroundDrawable(tintDrawable(drawable, ColorStateList.valueOf(mContext.getResources().getColor(android.R.color.holo_blue_light))));
} else {
viewHolder.icon.setBackgroundDrawable(tintDrawable(drawable, ColorStateList.valueOf(mContext.getResources().getColor(android.R.color.holo_green_light))));
}
private Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(wrappedDrawable, colors);
return wrappedDrawable;
}