Search code examples
androiddata-bindingloadimageandroid-binding-adapter

How we write raw string in a custom databinding attribute?


I write a custom attribute for load image url like this:

@BindingAdapter("srcCircleUrl")
fun loadCircleImage(view: ImageView, imageUrl: String) {
    loadImage(view.context, imageUrl, view, options = circleCropTransform())
}

when I want to set a raw string in xml, it gives me srcCircleUrl attribute not found error.

for example if I write something like this, it does not work:

<ImageView
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginBottom="16dp"
    app:srcCircleUrl="https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png"
    android:scaleType="centerCrop"
    tools:srcCompat="@drawable/flag_iran" />

so, the question is, how can I give a raw string as input to a custom databinding attribute?


I also test these ways:

app:srcCircleUrl="@{https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png}"

app:srcCircleUrl="@{`https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png`}"

Solution

  • You need to surround your string with single quotes and curly brackets like so app:something='@{"my string"}'.

    I think this should work for you:

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        app:srcCircleUrl='@{"https://66.media.tumblr.com/image.png"}'
        android:scaleType="centerCrop"
        tools:srcCompat="@drawable/flag_iran" />