Search code examples
androidkotlinandroid-databinding

How to databinding image loading with Glide?


I am trying to load image with databinding. But I never got over it. Where's my problem? Below is my code and layout construction.

MyItemViewModel.kt

  @BindingAdapter("imageUrl")
    fun loadImage(view: RoundedImageView, url: String) = Glide.with(view.context).load(url).into(view)

layout.xml

<data>

    <variable
            name="viewModel"
            type="com.myapp.app.ui.activity.albumlist.AlbumItemViewModel"/>
</data>

  <com.makeramen.roundedimageview.RoundedImageView
                android:layout_width="60dp"
                android:id="@+id/ivRoundedAlbum"
                android:layout_marginStart="@dimen/unit_20_dp"
                app:riv_corner_radius="8dp"
                app:imageUrl="@{viewModel.data.cover}"
                android:layout_height="60dp"/>

Solution

  • You need to make url parameter nullable, and guard against null like this:

    @BindingAdapter("imageUrl")
    fun loadImage(view: RoundedImageView, url: String?) {
        if (!url.isNullOrEmpty()) {
            .....
        }
    }