Created
September 30, 2023 15:17
-
-
Save arrazyfathan/26b1c3b6a8cfbeb5054cfcbc63a5bfa3 to your computer and use it in GitHub Desktop.
Reusable ListAdapter for simple list.
This file contains hidden or 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
abstract class BaseListAdapter<T, VB : ViewBinding>( | |
private val bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> VB, | |
diffUtil: DiffUtil.ItemCallback<T>, | |
) : ListAdapter<T, BaseListAdapter<T, VB>.ViewHolder>(diffUtil) { | |
inner class ViewHolder(val binding: VB, val context: Context) : | |
RecyclerView.ViewHolder(binding.root) { | |
fun bind(item: T, position: Int) { | |
bindItem(item, binding, position, context) | |
} | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { | |
val inflater = LayoutInflater.from(parent.context) | |
val binding = bindingInflater(inflater, parent, false) | |
return ViewHolder(binding, parent.context) | |
} | |
override fun onBindViewHolder(holder: ViewHolder, position: Int) { | |
holder.bind(getItem(position), position) | |
} | |
abstract fun bindItem(item: T, binding: VB, position: Int, context: Context) | |
} |
This file contains hidden or 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
class NotificationAdapter : BaseListAdapter<Notification, RvItemNotifBinding>( | |
RvItemNotifBinding::inflate, | |
DiffCallback(), | |
) { | |
private class DiffCallback : DiffUtil.ItemCallback<Notification>() { | |
override fun areItemsTheSame(oldItem: Notification, newItem: Notification): Boolean = | |
oldItem.id == newItem.id | |
override fun areContentsTheSame(oldItem: Notification, newItem: Notification): Boolean = | |
oldItem == newItem | |
} | |
override fun bindItem( | |
item: Notification, | |
binding: RvItemNotifBinding, | |
position: Int, | |
context: Context, | |
) { | |
with(binding) { | |
// ui | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment