Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"/>
like image 244
Hasan Kucuk Avatar asked Jul 04 '19 14:07

Hasan Kucuk


People also ask

Can I use Viewbinding with DataBinding?

The one and only function of View Binding is to bind the views in the code, while Data Binding offers some more options like Binding Expressions, which allows us to write expressions the connect variables to the views in the layout.


1 Answers

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

@BindingAdapter("imageUrl")
fun loadImage(view: RoundedImageView, url: String?) {
    if (!url.isNullOrEmpty()) {
        .....
    }
}
like image 123
IgorGanapolsky Avatar answered Oct 12 '22 21:10

IgorGanapolsky