Skip to content

Instantly share code, notes, and snippets.

@volo-droid
Created May 16, 2021 21:55
Show Gist options
  • Save volo-droid/a51a96f319d0c54edc3e27944886b35b to your computer and use it in GitHub Desktop.
Save volo-droid/a51a96f319d0c54edc3e27944886b35b to your computer and use it in GitHub Desktop.
Creating RecyclerView list adapter without extra adapter/view holder classes
fun <T : Any, B : ViewBinding> createListAdapter(
bindingInflater: (LayoutInflater) -> B,
bindData: B.(T) -> Unit,
): ListAdapter<T, *> = BindingListAdapter(bindingInflater, bindData)
class BindableViewHolder<T : Any, B : ViewBinding>(
private val binding: B,
private val bindData: B.(T) -> Unit,
) : RecyclerView.ViewHolder(binding.root) {
fun bindData(item: T) = binding.bindData(item)
}
open class BindingListAdapter<T : Any, B : ViewBinding>(
private val bindingInflater: (LayoutInflater) -> B,
private val bindData: B.(T) -> Unit,
) : ListAdapter<T, BindableViewHolder<T, B>>(ItemDiffCallback<T>()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
BindableViewHolder(bindingInflater(LayoutInflater.from(parent.context)), bindData)
override fun onBindViewHolder(holder: BindableViewHolder<T, B>, position: Int) =
holder.bindData(currentList[position])
final override fun getItemCount(): Int = super.getItemCount()
}
class ItemDiffCallback<T : Any> : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = oldItem::class.java == newItem::class.java
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment