在使用Glide加载图片时,若是出现“You must not call setTag() on a view Glide is targeting”的错误,八成是在使用ListView的时候出现的。简单来讲就是本来想简化布局文件的代码,可是很不幸,这样作却会形成错误。android
若是出错了,你的item八成是这个样子:ide
<?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等均可以)spa
若是追踪错误来源,会找到这里:.net
@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中:code
convertView.setTag(holder);
这句代码等同于:xml
imageview.setTag(holder);
这样的话,getTag()的对象就不为Request,从而抛出异常。对象
那Glide为啥要给ImageView设置Tag呢?缘由也很容易想到:
Glide给ImageView设置Tag的缘由是为了防止图片加载错乱blog
在评论区中,一叶飘舟指出了:使用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" />
转载请标明出处:http://blog.csdn.net/qq_26411333/article/details/52034444