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"/>
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.
You need to make url parameter nullable, and guard against null like this:
@BindingAdapter("imageUrl")
fun loadImage(view: RoundedImageView, url: String?) {
if (!url.isNullOrEmpty()) {
.....
}
}
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