如何处理 Glide V4 中未找到图像的错误

How to handle image not found error in Glide V4

我试图在 Glide 中处理图像未找到 (404) 错误,但它没有编译:

Glide.with(this@ImageActivity)
                        .addDefaultRequestListener(
                                object:RequestListener<Drawable> {
                                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                    }

                                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                    }

                                }

                        )
                        .load(imageURL).apply(requestOptions)
                        .into(imageview)

但是编译器在 object:RequestListener 上引发了这个错误:

Type mismatch: inferred type is but RequestListener! was expected

你必须像这样使用 submit() -

Glide.with(this@ProfileActivity).load(imageURL).into(imageview)
              .listener(object : RequestListener<Drawable> {
                  override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                      //TODO handle error images while loading photo
                      return true
                  }

                  override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                      //TODO use "resource" as the photo for your ImageView
                      return true
                  }

              }).submit()

如果你想使用addDefaultRequestListener,你需要使用Any而不是Drawable

Glide.with(context).addDefaultRequestListener(object : RequestListener<Any> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: com.bumptech.glide.request.target.Target<Any>?, isFirstResource: Boolean): Boolean {
            }

            override fun onResourceReady(resource: Any?, model: Any?, target: com.bumptech.glide.request.target.Target<Any>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
            }

        })

您可以通过placeholder()方法简单地使用Glide。您可以使用以下方法。

private fun fetchImage(imageView: ImageView, url: String){
    Glide
        .with(this)
        .load(url)
        .centerCrop()
        .placeholder(R.drawable.ic_menu_camera)
        .into(imageView)
}