Skip to content

Instantly share code, notes, and snippets.

@kozmi55
Last active August 16, 2021 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kozmi55/1b2e0a4c8986bc276fcb8f32d5c7974e to your computer and use it in GitHub Desktop.
Save kozmi55/1b2e0a4c8986bc276fcb8f32d5c7974e to your computer and use it in GitHub Desktop.
class BindableRecyclerViewAdapter : RecyclerView.Adapter<BindableViewHolder>() {
var itemViewModels: List<ItemViewModel> = emptyList()
private val viewTypeToLayoutId: MutableMap<Int, Int> = mutableMapOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindableViewHolder {
val binding: ViewDataBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
viewTypeToLayoutId[viewType] ?: 0,
parent,
false)
return BindableViewHolder(binding)
}
override fun getItemViewType(position: Int): Int {
val item = itemViewModels[position]
if (!viewTypeToLayoutId.containsKey(item.viewType)) {
viewTypeToLayoutId[item.viewType] = item.layoutId
}
return item.viewType
}
override fun getItemCount(): Int = itemViewModels.size
override fun onBindViewHolder(holder: BindableViewHolder, position: Int) {
holder.bind(itemViewModels[position])
}
fun updateItems(items: List<ItemViewModel>?) {
itemViewModels = items ?: emptyList()
notifyDataSetChanged()
}
}
class BindableViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(itemViewModel: ItemViewModel) {
binding.setVariable(BR.itemViewModel, itemViewModel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment