如果无法加载url,如何加载我的占位符?

时间:2019-06-25 11:16:05

标签: android error-handling drawable android-drawable android-glide

我正在尝试使用Glide加载图像。 我给了它一个URL,但是它导致FileNotFound异常。 但是,这与我无关,我的担心是,如果发生任何这些错误,我想加载一个占位符。 我按照指南使用滑行,但没有任何反应。 请看一下我的代码。

我尝试添加RequestListener和错误回退。

       Glide.with(imageView.getContext()).load(url)      
       .transition(DrawableTransitionOptions.withCrossFade())
       .apply(new RequestOptions().placeholder(placeholder))
       .error(Glide.with(imageView.getContext()).load(placeholder))
       .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(imageView);

我希望将占位符加载到imageview中。 实际结果是我的imageview加载了一些我自己未定义的占位符,这表明该图像链接被禁止或其他原因。 预期:我希望加载占位符。

6 个答案:

答案 0 :(得分:0)

这里是修改后的代码:

int placeholder = R.drawable.placeholder

Glide.with(imageView.getContext())
            .load(url)
            .error(placeholder)
            .placeholder(placeholder)
            .into(imageView);

答案 1 :(得分:0)

尝试一下:

int placeholder = R.drawable.error 
GlideApp.with(imageView.getContext())
          .load(url)
          .apply(new RequestOptions().placeholder(placeholder)
              .error(placeholder).dontTransform()
              .diskCacheStrategy(DiskCacheStrategy.ALL))
          .into(mImageView);

答案 2 :(得分:0)

如果出现错误,您可以参考下面的代码来显示placeholder图像:

 Glide.with(context).load(BASE_URL + imageUrl)
                    .apply(new RequestOptions().placeholder(R.drawable.defaultimage)
                            .error(R.drawable.defaultimage)).into(imageView);

答案 3 :(得分:0)

尝试使用此-

.error(getResourses.getDrawable(R.drawable.placeholder))

而不是使用此-

.error(Glide.with(imageView.getContext()).load(placeholder))

答案 4 :(得分:0)

在下面尝试使用此代码。

Glide.with(your context).load(imageurl).apply(RequestOptions.placeholderOf(your drawable here)).error(your error drawable).into(your imageview);

希望它能起作用...

答案 5 :(得分:0)

尝试使用RequestOptions

RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_placeholder);
requestOptions.error(R.drawable.ic_error);

Glide.with(context)
     .load(url)
     .apply(requestOptions)
     .into(holder.imageView);