Last active
January 26, 2024 07:34
-
-
Save gab-stargazer/77a1fd5bf7a751e4d7e97772c0ca26f5 to your computer and use it in GitHub Desktop.
Dynamic Recyclerview Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.SuppressLint | |
import android.view.LayoutInflater | |
import android.view.ViewGroup | |
import androidx.recyclerview.widget.DiffUtil | |
import androidx.recyclerview.widget.ListAdapter | |
import androidx.recyclerview.widget.RecyclerView | |
import androidx.viewbinding.ViewBinding | |
class DynamicAdapter<T : Any, VB : ViewBinding>( | |
private val inflate: (LayoutInflater, ViewGroup, Boolean) -> VB, | |
private val onBind: VB.(T) -> Unit, | |
diffUtil: DiffUtil.ItemCallback<T> = GenericDiffUtilCallback() | |
) : ListAdapter<T, DynamicAdapter<T, VB>.ViewHolder>(diffUtil) { | |
inner class ViewHolder(private val binding: VB) : | |
RecyclerView.ViewHolder(binding.root) { | |
fun bind(item: T) { | |
onBind(binding, item) | |
} | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { | |
val inflater = LayoutInflater.from(parent.context) | |
val binding = inflate(inflater, parent, false) | |
return ViewHolder(binding) | |
} | |
override fun onBindViewHolder(holder: ViewHolder, position: Int) { | |
getItem(position)?.let { | |
holder.bind(it) | |
} | |
} | |
class GenericDiffUtilCallback<T : Any> : DiffUtil.ItemCallback<T>() { | |
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean { | |
return oldItem === newItem | |
} | |
@SuppressLint("DiffUtilEquals") | |
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean { | |
return oldItem == newItem | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DynamicAdapter<Item, ItemBinding>( | |
inflate = { inflater, parent, attachToParent -> | |
ListItemBinding.inflate(inflater, parent, attachToParent) | |
}, | |
onBind = { item -> | |
tvTitle.text = item.title | |
tvSubtitle.text = item.subtitle | |
tvMsg.text = item.content | |
}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment