1+ package com.codinginflow.imagesearchapp.ui.gallery
2+
3+ import android.view.LayoutInflater
4+ import android.view.ViewGroup
5+ import androidx.paging.PagingDataAdapter
6+ import androidx.recyclerview.widget.DiffUtil
7+ import androidx.recyclerview.widget.RecyclerView
8+ import com.bumptech.glide.Glide
9+ import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
10+ import com.codinginflow.imagesearchapp.R
11+ import com.codinginflow.imagesearchapp.data.UnsplashPhoto
12+ import com.codinginflow.imagesearchapp.databinding.ItemUnsplashPhotoBinding
13+
14+ class UnsplashPhotoAdapter :
15+ PagingDataAdapter <UnsplashPhoto , UnsplashPhotoAdapter .PhotoViewHolder >(PHOTO_COMPARATOR ) {
16+
17+ override fun onCreateViewHolder (parent : ViewGroup , viewType : Int ): PhotoViewHolder {
18+ val binding =
19+ ItemUnsplashPhotoBinding .inflate(LayoutInflater .from(parent.context), parent, false )
20+
21+ return PhotoViewHolder (binding)
22+ }
23+
24+ override fun onBindViewHolder (holder : PhotoViewHolder , position : Int ) {
25+ val currentItem = getItem(position)
26+
27+ if (currentItem != null ) {
28+ holder.bind(currentItem)
29+ }
30+ }
31+
32+ class PhotoViewHolder (private val binding : ItemUnsplashPhotoBinding ) :
33+ RecyclerView .ViewHolder (binding.root) {
34+
35+ fun bind (photo : UnsplashPhoto ) {
36+ binding.apply {
37+ Glide .with (itemView)
38+ .load(photo.urls.regular)
39+ .centerCrop()
40+ .transition(DrawableTransitionOptions .withCrossFade())
41+ .error(R .drawable.ic_error)
42+ .into(imageView)
43+
44+ textViewUserName.text = photo.user.username
45+ }
46+ }
47+ }
48+
49+ companion object {
50+ private val PHOTO_COMPARATOR = object : DiffUtil .ItemCallback <UnsplashPhoto >() {
51+ override fun areItemsTheSame (oldItem : UnsplashPhoto , newItem : UnsplashPhoto ) =
52+ oldItem.id == newItem.id
53+
54+ override fun areContentsTheSame (oldItem : UnsplashPhoto , newItem : UnsplashPhoto ) =
55+ oldItem == newItem
56+ }
57+ }
58+ }
0 commit comments