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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With