Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding bindingadapter with multiple parameters not working

I´m trying to use databinding for loading an image with Glide, Imageview and Bindingadapter with multiple parameters:

@BindingAdapter(value = ["url", "defaultImage", "placeholder", "circleCrop"], requireAll = false)
fun ImageView.setImageUrl(url: String, defaultResId: Int? = null, placeHolderResId: Int? = null, circleCrop: Boolean = false) {
    val glideRequest = if (defaultResId != null) GlideApp.with(context).loadOrDefault(url, defaultResId)
    else GlideApp.with(context).load(url)
    if (placeHolderResId != null) glideRequest.placeholder(placeHolderResId)
    if (circleCrop) glideRequest.circleCrop()
    glideRequest.into(this)
}

<ImageView
        android:id="@+id/imgProfile"
        android:layout_width="@dimen/size_avatar_search_result"
        android:layout_height="0dp"
        app:circleCrop="@{true}"
        app:defaultImage="@{@drawable/default_avatar}"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:placeholder="@{@drawable/default_avatar}"
        app:url="@{item.profilePhotoUrl}"
        tools:src="@drawable/default_avatar" />

The bindingadapter method is a top level function. When compiling I get the databinding-kapt error 'Cannot find the setter for attribute 'app:circleCrop' with parameter type boolean on android.widget.ImageView', as if my bindingadapter is not recognized. Not sure what I´m doing wrong

like image 232
Lemao1981 Avatar asked Feb 20 '18 07:02

Lemao1981


1 Answers

Even though, that compiler says the problem is with app:circleCrop, the actual problem is with the defaultResId and placeholderResId.

When using drawables in xml @{@drawable/default_avatar}, it is always compiled into Drawable.

Therefore your binding adapter has to have signature:

@BindingAdapter(value = ["url", "defaultImage", "placeholder", "circleCrop"], requireAll = false)
fun ImageView.setImageUrl(url: String, default: Drawable? = null, placeholder: Drawable? = null, circleCrop: Boolean = false) {
  // code
}

You can see the result when you look at the generated code (e.g for layout fragment_something.xml it usually is FragmentSomethingBinding) and there you would see that the drawable resource uses getDrawableFromResource() function.

like image 106
mlykotom Avatar answered Oct 13 '22 00:10

mlykotom