关于安卓setBackgroundColor中Drawable复用导致背景重复改变

先看问题代码:

if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {

            if (background == null && bkcolor == -1) {
                Drawable drawable = viewHolder.itemView.getBackground();
                if (drawable == null) {
                    bkcolor = 0;
                } else {
                    background = drawable;
                }
            }
            LogUtil.d("viewHolder",((MarketingEventRecyclerAdapter.MyViewHolder )viewHolder).mTvItemMarketingEventTitle.getText().toString());
            ((MarketingEventRecyclerAdapter.MyViewHolder) viewHolder).mTvItemMarketingEventTitle.setText(((MarketingEventRecyclerAdapter.MyViewHolder) viewHolder).mTvItemMarketingEventTitle.getText()+"-");

            viewHolder.itemView.setBackgroundColor(Color.RED);//看这句
        }

问题重现:
先点击标题为0的:

第一个item被选中,同时我在标题中加了一个横线
第一个item被选中,同时我在标题中加了一个横线

再点击标题为3的:

第三个item被选中
第三个item被选中

再次点击标题为0的:

这里写图片描述

标题为0的和标题为3的同时变成红色了

控制台打印的log:
09-18 07:55:29.832 11934-11934/com.wecool.card D/viewHolder: 0
09-18 07:56:33.695 11934-11934/com.wecool.card D/viewHolder: 3
09-18 07:58:17.490 11934-11934/com.wecool.card D/viewHolder: 0-

下面我们看setBackgroundColor方法的源码:

@RemotableViewMethod
    public void setBackgroundColor(@ColorInt int color) {
        if (mBackground instanceof ColorDrawable) {
            ((ColorDrawable) mBackground.mutate()).setColor(color);
            computeOpaqueFlags();
            mBackgroundResource = 0;
        } else {
            setBackground(new ColorDrawable(color));
        }
    }

其中调用了mutate()方法,mutate()方法是这样描述的:
Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

翻译:
使这个drawable变得可变。 此操作无法反转。 一个可变的drawable保证不与任何其他drawable共享其状态。 当您需要修改从资源加载的drawable属性时,这是非常有用的。 默认情况下,从同一资源加载的所有drawable实例共享一个共同的状态; 如果您修改一个实例的状态,则所有其他实例都将收到相同的修改。 在可变的Drawable上调用此方法将不起作用。

也就是说item的背景Drawable会被复用

那么我们将代码改成

viewHolder.itemView.setBackground(new ColorDrawable(Color.Red));

问题便解决了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值