您的位置:

glide出现IllegalStateException("You cannot use a request as both the main request and a "+ "thumbnail, consider using clone() on the request(s) passed to thumbnail()")的解决方案

  发布时间:2023-01-25 14:30:01
例如,可以使用以下代码将图像加载到ImageView,并使用缩略图:<pre><code class='java'>RequestBuilder<Drawable> mainRequestBuilder = Glide.with.load;RequestBuilder<Drawable> thumbnailRequestBuilder = Glide.with.load.clone();Glide.with .load .thumbnail .into;这样做会先加载缩略图,再加载主图,这样可以先显示缩略图,再加载主图,防止等待过长导致的用户等待不耐烦。注意,如果你在 Activity/Fragment中使用Glide,在 onStop() 方法中调用 Glide.with.clear 清除请求,这样可以避免内存泄漏。

报错的原因

在使用Glide库时,如果同时使用了单个请求作为主请求和缩略图请求,会导致出现"IllegalStateException("You cannot use a request as both the main request and a "+ "thumbnail, consider using clone() on the request(s) passed to thumbnail()")"错误。这是因为Glide不允许使用同一个请求作为主请求和缩略图请求,需要使用clone()方法创建一个新的请求来作为缩略图请求。

如何解决

解决方法是在使用缩略图请求时,使用clone()方法创建一个新的请求。

例如,可以使用以下代码将图像加载到ImageView,并使用缩略图


RequestBuilder mainRequestBuilder = Glide.with(context).load(imageUrl);
RequestBuilder thumbnailRequestBuilder = Glide.with(context).load(thumbnailUrl).clone();

Glide.with(context)
    .load(imageUrl)
    .thumbnail(thumbnailRequestBuilder)
    .into(imageView);

这样做会先加载缩略图,再加载主图,这样可以先显示缩略图,再加载主图,防止等待过长导致的用户等待不耐烦。

使用例子

是的,下面是一个使用Glide加载图像并使用缩略图的示例代码:


String imageUrl = "https://example.com/image.jpg";
String thumbnailUrl = "https://example.com/thumbnail.jpg";

ImageView imageView = findViewById(R.id.image_view);

RequestBuilder mainRequestBuilder = Glide.with(this).load(imageUrl);
RequestBuilder thumbnailRequestBuilder = Glide.with(this).load(thumbnailUrl).clone();

Glide.with(this)
    .load(imageUrl)
    .thumbnail(thumbnailRequestBuilder)
    .into(imageView);

这段代码首先创建两个请求,一个用于加载主图,另一个用于加载缩略图。 然后使用`thumbnail()`方法将缩略图请求添加到主请求中,最后使用`into()`方法将图像加载到ImageView。

注意,如果你在 Activity/Fragment中使用Glide,在 onStop() 方法中调用 Glide.with(this).clear(imageView) 清除请求,这样可以避免内存泄漏。