Skip to content

Instantly share code, notes, and snippets.

@faruktoptas
Created August 3, 2020 08:22
Show Gist options
  • Save faruktoptas/0968b6cfac560fc0a2c16b84370730f5 to your computer and use it in GitHub Desktop.
Save faruktoptas/0968b6cfac560fc0a2c16b84370730f5 to your computer and use it in GitHub Desktop.
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.support.annotation.IdRes
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
abstract class BaseBindingListAdapter<T, in DB : ViewDataBinding> : RecyclerView.Adapter<BaseBindingListAdapter<T, DB>.BaseViewHolder>() {
var items: List<T>? = null
set(value) {
field = value
notifyDataSetChanged()
}
var itemClickListener: ((T) -> Unit)? = null
abstract fun layoutResource(): Int
abstract fun bindingVariableId(): Int
open fun bind(holder: BaseViewHolder, item: T?, position: Int) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate<DB>(layoutInflater, layoutResource(), parent, false)
return BaseViewHolder(binding, bindingVariableId())
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
items?.let {
val item = it[position]
holder.bind(item)
bind(holder, item, position)
holder.itemView.setOnClickListener {
itemClickListener?.invoke(item)
}
bind(holder, item, position)
}
}
override fun getItemCount() = items?.size ?: 0
inner class BaseViewHolder(val binding: ViewDataBinding, private val variableId: Int) : RecyclerView.ViewHolder(binding.root) {
private val views = hashMapOf<Int, View>()
fun <T : View> getItemById(@IdRes id: Int): T {
if (!views.containsKey(id)) {
views[id] = itemView.findViewById<T>(id)
}
return views[id] as T
}
fun bind(item: T?) {
binding.setVariable(variableId, item)
binding.executePendingBindings()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment