Skip to content

Instantly share code, notes, and snippets.

@wenqin-231
Last active April 14, 2020 08:53
Show Gist options
  • Save wenqin-231/70ee973b6d130e7e247360ee6d6021ad to your computer and use it in GitHub Desktop.
Save wenqin-231/70ee973b6d130e7e247360ee6d6021ad to your computer and use it in GitHub Desktop.
BindingAdapter
open class BindViewHolder<VB : ViewBinding, T> : RecyclerView.ViewHolder {
private val vb: VB
private constructor(vb: VB) : super(vb.root) {
this.vb = vb
}
constructor(parent: ViewGroup, callback: (LayoutInflater, ViewGroup, Boolean) -> VB) :
this(parent.run { callback.invoke(LayoutInflater.from(context), this, false) })
fun update(item: T) {
vb.apply {
onUpdate(item).invoke(vb)
}
}
open fun onUpdate(item: T): VB.() -> Unit = {}
}
abstract class BindAdapter<T, VH : BindViewHolder<*, T>> : RecyclerView.Adapter<VH>() {
private val data: MutableList<T> = arrayListOf()
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: VH, position: Int) {
data.getOrNull(position)?.apply {
holder.update(this)
}
}
}
@wenqin-231
Copy link
Author

wenqin-231 commented Apr 14, 2020

Usage

class ItemVH(parent: ViewGroup) : BindViewHolder<ListItemSearchBinding, ChatMessage>(parent, ListItemSearchBinding::inflate) {

    override fun onUpdate(item: ChatMessage): ListItemSearchBinding.() -> Unit = {
        tvContent.text = item.description
    }
}

class MyAdapter : BindAdapter<ChatMessage, BindViewHolder<*, ChatMessage>>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindViewHolder<*, ChatMessage> {
        return when (viewType) {
            0 -> ItemVH(parent)
            else -> OtherItemVH(parent)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment