Thursday, 29 August 2024

View Image url from api to ImageView in RecyclerView Adapter class Using DataBinding

 1. build.gradle.kts

dependencies{
//image  loader
implementation(libs.androidx.glide.bumptech)
}
plugins {
id("org.jetbrains.kotlin.kapt")
}
2. libs.version.toml
androidx-glide-bumptech={group="com.github.bumptech.glide",name="glide",version="4.16.0"}
3.Create a databinding utils class like below:
package com.example.mvvmtest3

import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import java.net.URL

@BindingAdapter("android:bindImage")
fun loadImage(view: ImageView, url: String) {
Glide.with(view)
.load(url)
.into(view)
}
4. recycler_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>

<variable
name="album"
type="com.example.mvvmtest3.model.AlbumResponseItem" />
</data>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
    android:layout_width="100dp"
android:bindImage="@{album.title}"
android:id="@+id/imageView"
android:contentDescription="@string/app_name"
android:layout_height="100dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_toRightOf="@+id/imageView"
android:orientation="vertical">

<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="@{album.title}"
android:textColor="@color/black"
android:textStyle="bold" />

<TextView
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{String.valueOf(album.id)}" />

<TextView
android:id="@+id/userId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="@{String.valueOf(album.userId)}" />

</LinearLayout>

</RelativeLayout>
</androidx.cardview.widget.CardView>

</LinearLayout>
</layout>

No comments:

Post a Comment