如何在 Kotlin 中设置带有复合可绘制对象的 TextView,该复合可绘制对象是 URL 图像,加载了 Glide?

How to set a TextView with a compound drawable that is a URL image, loaded with Glide, in Kotlin?

这是我尝试的代码。

val imageView = ImageView(holder.itemView.context)

holder.itemView.textView.setCompoundDrawablesWithIntrinsicBounds(
        GlideApp.with(holder.itemView.context).load(URL).into(imageView), 0, 0, 0)

我也不确定 Glide 的图像目标。我把它设置为 .into(imageView)。因为我想用 TextView 添加图像,所以没有初始化 ImageView 来加载 URL 图像。我的想法是以编程方式创建一个

val imageView = ImageView(holder.itemView.context)

我看到的错误是 GlideApp.with(holder.itemView.context).load(URL).into(imageView) 未被检测为可绘制对象。

您应该在 xml 布局中创建 imageView。 在你的情况下这样做

    Glide.with(applicationContext)
                       .load("https://LINK")
                       .listener(object : RequestListener<Drawable> {
                           override fun onLoadFailed(
                                   glideException: GlideException?,
                                   any: Any?,
                                   target: com.bumptech.glide.request.target.Target<Drawable>?,
                                   exception: Boolean
                           ): Boolean {

                               return false
                           }

                           override fun onResourceReady(
                                   drawable: Drawable?,
                                   any: Any?,
                                   target: com.bumptech.glide.request.target.Target<Drawable>?,
                                   dataSource: DataSource?,
                                   resources: Boolean
                           ): Boolean {
                               //check this on how to set drawable to textView
//
                               //set drawable to textView or do whatever you want with drawable

                               return false
                           }
                       })
                       .submit()

在 Kotlin 中你可以这样做:

 Glide.with(context).load("url").apply(RequestOptions().fitCenter()).into(
        object : CustomTarget<Drawable>(50,50){
            override fun onLoadCleared(placeholder: Drawable?) {
                textView.setCompoundDrawablesWithIntrinsicBounds(placeholder, null, null, null)
            }

            override fun onResourceReady(
                resource: Drawable,
                transition: Transition<in Drawable>?
            ) {
                textView.setCompoundDrawablesWithIntrinsicBounds(resource, null, null, null)
            }
        }
    )