Generic Base Recyclerview Adapter with ViewBinding & Multiple View Click Support
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
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