Last active
April 14, 2020 08:53
-
-
Save wenqin-231/70ee973b6d130e7e247360ee6d6021ad to your computer and use it in GitHub Desktop.
BindingAdapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage