Why is this BindingAdapter not working in Kotlin?

前端 未结 3 2119
予麋鹿
予麋鹿 2021-01-06 01:30

I have a ViewModel with:

val imageUrl = ObservableField()

My layout XML has:



        
3条回答
  •  天涯浪人
    2021-01-06 01:44

    I've had a different problem. This may not be the solution for your problem, but maybe others will benefit from it. What I did in plus was to add a placeholder and an error drawable as well to my load image function like this:

    @JvmStatic
    @BindingAdapter("imageUrl", "error", "placeholder")
    fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
        Picasso.get()
                .load(imageUrl)
                .placeholder(placeholder
                        ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
                .error(error
                        ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
                .into(this)
    }
    

    I tought that putting the ? to the end of the Drawables was enough and in the layout I could just provide the image URL with app:imageUrl, if I didn't want to provide any specific error and placeholder images. But I was wrong, I kept getting the same error as you, Cannot find setter... After a few hours of clearing the cache, deleting every build folder, restarting android studio a few times, I found the solution in a google provided guide. You need to specify inside the @BindingAdapter if all of the attributes are required or not. So I modified my code like this and it worked:

    @JvmStatic
    @BindingAdapter(value = ["imageUrl", "error", "placeholder"], requireAll = false)
    fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
        Picasso.get()
                .load(imageUrl)
                .placeholder(placeholder
                        ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
                .error(error
                        ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
                .into(this)
    }
    

提交回复
热议问题