Drawable着色问题

方法一: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>


  然后奇葩问题出现了,明明在代码中给偶数下标的Image设置了着色,结果一个都没有生效。。。

  这里可以用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);


方法二:DrawableCompat(向后兼容)

        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;
    }








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值