Skip to content

Instantly share code, notes, and snippets.

@mustafayigitt
Last active January 4, 2022 13:03
Show Gist options
  • Save mustafayigitt/0073cf0a9a8cb52c016b83737c47a495 to your computer and use it in GitHub Desktop.
Save mustafayigitt/0073cf0a9a8cb52c016b83737c47a495 to your computer and use it in GitHub Desktop.
Generic Base Recyclerview Adapter with ViewBinding & Multiple View Click Support
abstract class BaseRecyclerAdapter<T : BaseComparable, VB : ViewBinding>(
private inline val bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> VB,
private inline val onBind: (item: T, binding: VB) -> Unit,
private inline val actions: (VB) -> List<Pair<View, (T) -> Unit>>,
) : ListAdapter<T, BaseRecyclerAdapter<T, VB>.BaseViewHolder>(BaseDiffCallback<T>()) {
inner class BaseViewHolder(
val binding: VB
) : RecyclerView.ViewHolder(binding.root) {
init {
actions(binding).forEach { actionPair ->
actionPair.first.setOnClickListener {
actionPair.second(currentList[bindingAdapterPosition])
}
}
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): BaseRecyclerAdapter<T, VB>.BaseViewHolder {
val binding = bindingInflater(
LayoutInflater.from(parent.context),
parent,
false
)
return BaseViewHolder(binding)
}
override fun onBindViewHolder(
holder: BaseRecyclerAdapter<T, VB>.BaseViewHolder,
position: Int
) {
onBind.invoke(currentList[position], holder.binding)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment