You must not call setTag() on a view Glide is targeting的解決方案

原文鏈接:https://blog.csdn.net/qq_26411333/article/details/52034444

概述

在使用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);

    1

這句代碼等同於:

imageview.setTag(holder);

    1

這樣的話,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
    2
    3
    4
    5

結語

    如果使用ListView,只需改變item的佈局就可以解決問題,不要太糾結。
    如果想要佈局簡潔,不用改變佈局文件,使用RecyclerView來代替ListView。
————————————————
版權聲明:本文爲CSDN博主「尹凱文」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_26411333/article/details/52034444

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章