关于加载失败的滑翔

时间:2018-02-15 07:51:53

标签: java android android-glide

我在我的应用程序中使用glide for load image。它的工作正常,我的条件如

if(image_enabled==1){
Glide.with(getContext()).load(constant.SERVER_URL+"images/"+quoteData.get(KEY_PICTURE).apply(myOptions).into(mImageView);
}

else if(image_enabled==0){
Glide.with(getContext()).load(constant.SERVER_URL+"images/"+quoteData.get(KEY_PICTURE)).apply(myOptions).into(mImageView);
}

但是如果任何上述条件无法加载图片,我想再加载一个url。我不知道哪种方法可以在滑行中使轨道加载失败。让我知道是否有人可以帮助我获得它。 感谢

2 个答案:

答案 0 :(得分:1)

我认为这会对你有所帮助。只需在.error()中设置您的网址,它就会在失败时加载。

Glide.with(getContext())
      .load("your url")
      .error("your default drawable")
      .into(mImgProfile);

否则你也可以在下面使用

Glide.with(mActivity)
     .load("your url")
     .listener(new RequestListener<String, GlideDrawable>() {
         @Override
         public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            return false;
         }

         @Override
         public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                return false;
         }
       })
     .into(mImgProfile);

答案 1 :(得分:0)

如果当前加载失败,这里完全可行的代码加载另一个网址:

代码重用的小扩展:

fun RequestBuilder<Drawable>.setListener(
    onReady: () -> Boolean = { false },
    onFailed: () -> Boolean,
): RequestBuilder<Drawable> {
    return listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean,
        ): Boolean = onFailed()

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean,
        ): Boolean = onReady()
    })
}

来自 ViewHolder 的代码示例:

private val avatarImage = view.findViewById<ImageView>(R.id.avatar_image)

private val glideHandler = Handler(Looper.getMainLooper())

fun bind(urlList: List<String>) {
    if (urlList.isNotEmpty()) {
        loadImage(urlList)
   }
}

fun unbind() {
    glideHandler.removeCallbacksAndMessages(null)
}

private fun loadImage(urlList: List<String>, index: Int = urlList.indices.first) {
    val url = urlList.getOrNull(index) ?: return

    Glide.with(avatarImage)
        .load(url)
        .placeholder(R.drawable.img_holder_load)
        .error(R.drawable.img_holder_error)
        .setListener {
            val newIndex = index + 1

            if (newIndex in urlList.indices) {
                glideHandler.post { loadImage(urlList, newIndex) }
                return@setListener true
            }

            return@setListener false
        }
        .into(avatarImage)
}