Skip to content

Instantly share code, notes, and snippets.

@jakubkinst
Last active June 11, 2018 08:46
Show Gist options
  • Save jakubkinst/0c70dc2f74e2b7b07e79be43cd2e0fe2 to your computer and use it in GitHub Desktop.
Save jakubkinst/0c70dc2f74e2b7b07e79be43cd2e0fe2 to your computer and use it in GitHub Desktop.
RecyclerView Data Binding
open class DataBoundAdapter<T>(val lifecycleOwner: LifecycleOwner, val itemLayoutIdProvider: (T) -> Int, val bindingVariableId: Int, diffCallback: DiffUtil.ItemCallback<T>) : ListAdapter<T, DataBoundViewHolder>(diffCallback) {
constructor(lifecycleOwner: LifecycleOwner, @LayoutRes itemLayoutId: Int, bindingVariableId: Int, diffCallback: DiffUtil.ItemCallback<T>) : this(lifecycleOwner, { itemLayoutId }, bindingVariableId, diffCallback)
private val extras = hashMapOf<Int, Any>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBoundViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
binding.setLifecycleOwner(lifecycleOwner)
return DataBoundViewHolder(binding)
}
override fun getItemViewType(position: Int) = itemLayoutIdProvider.invoke(getItem(position))
override fun onBindViewHolder(holder: DataBoundViewHolder, position: Int) {
holder.binding.setVariable(bindingVariableId, getItem(position))
extras.forEach { (varId, extra) -> holder.binding.setVariable(varId, extra) }
holder.binding.executePendingBindings()
}
fun bindExtra(bindingVariableId: Int, extra: Any) = this.also {
extras.put(bindingVariableId, extra)
}
}
class DataBoundViewHolder constructor(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)
@BindingAdapter("app:adapter", "app:items", requireAll = false)
fun <T> RecyclerView.setDataBoundAdapter(adapter: DataBoundAdapter<T>?, items: List<T>?) {
if (this.adapter == null)
this.adapter = adapter
(this.adapter as DataBoundAdapter<T>).submitList(items)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment