You must not call setTag() on a view Glide is targeting

概述

在使用Glide加载图片时,如果出现“You must not call setTag() on a view Glide is targeting”的错误,八成是在使用ListView的时候出现的。简单来说就是原本想简化布局文件的代码,但是很不幸,这样做却会造成错误

解决方案1

如果出错了,你的item八成是这个样子:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" />

使用Glide不会出错的item布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>

只要在ImageView的外层再加一层父布局,就不会有问题了(LinearLayout,RelativeLayout等都可以)

原因分析

如果追踪错误来源,会找到这里:

@Override
public Request getRequest() {
    Object tag = getTag();
    Request request = null; if (tag != null) { if (tag instanceof Request) { request = (Request) tag; } else { throw new IllegalArgumentException("You must not call setTag() on a view Glide is targeting"); } } return request; }

ImageView中的Tag需要强转成Request。如果,item中只有ImageView,那么在Adapter中:

convertView.setTag(holder);

这句代码等同于:

imageview.setTag(holder);

这样的话,getTag()的对象就不为Request,从而抛出异常。

那Glide为啥要给ImageView设置Tag呢?原因也很容易想到: 
Glide给ImageView设置Tag的原因是为了防止图片加载错乱

解决方案2

在评论区中,一叶飘舟指出了:使用RecyclerView,可以避免该问题,即使布局文件中的代码为下面的代码,也不会出错

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" />

 

结语

  1. 如果使用ListView,只需改变item的布局就可以解决问题,不要太纠结。
  2. 如果想要布局简洁,不用改变布局文件,使用RecyclerView来代替ListView

转载请标明出处:http://blog.csdn.net/qq_26411333/article/details/52034444

转载于:https://www.cnblogs.com/minghualiyan/p/5996363.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值