开发中经常会遇到这种情况,就是同一个图标需要不同的颜色,很多的时候需要美工提供不同颜色的图标,但DrawableCompat提供了一个很好地方法对图标颜色进行更改
private Drawable changeColor(@DrawableRes int drawableId, @ColorRes int colorId) { Drawable drawable = ContextCompat .getDrawable(this, drawableId) .mutate(); Drawable wrappedDrawable = DrawableCompat.wrap(drawable); ColorStateList colors = ColorStateList.valueOf(ContextCompat.getColor(this, colorId)); DrawableCompat.setTintList(wrappedDrawable, colors); return wrappedDrawable; }以上是自定义的一个修改图标颜色的方法
imageView1.setBackgroundDrawable(changeColor(R.drawable.ic_launcher, android.R.color.holo_blue_dark)); imageView2.setBackgroundDrawable(changeColor(R.drawable.ic_launcher, android.R.color.holo_red_dark));
直接调用即可,显示如下,第三个是默认图标