Skip to content

Instantly share code, notes, and snippets.

@travisdachi
Last active January 21, 2017 14:13
Show Gist options
  • Save travisdachi/7baf07cb84619876f4614c0578673ed3 to your computer and use it in GitHub Desktop.
Save travisdachi/7baf07cb84619876f4614c0578673ed3 to your computer and use it in GitHub Desktop.
abstract class ItemViewHolder<T : Any, VH>(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var item: T
var onClick: ((view: View, position: Int, holder: VH, item: T) -> Unit)? = null
init {
itemView.setOnClickListener { callOnClick(it) }
}
fun callOnClick(view: View) {
onClick?.let {
it.invoke(view, adapterPosition, this@ItemViewHolder as VH, item)
}
}
}
abstract class RvListAdapter<T : Any, VH : ItemViewHolder<T, VH>> @JvmOverloads constructor(
list: List<T>? = null,
val onItemClick: ((view: View, position: Int, holder: VH, item: T) -> Unit)? = null,
val diff: ((oldList: List <T>, newList: List<T>) -> DiffUtil.DiffResult)? = null
) : RecyclerView.Adapter<VH>() {
var list: List<T> by Delegates.observable(list ?: emptyList(), { kProperty, oldList, newList ->
if (diff != null) {
diff.invoke(oldList, newList).dispatchUpdatesTo(this)
} else {
notifyDataSetChanged()
}
})
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH = onCreateViewHolder(parent, viewType, LayoutInflater.from(parent.context)).apply {
onClick = onItemClick
}
abstract fun onCreateViewHolder(parent: ViewGroup, viewType: Int, inflater: LayoutInflater): VH
override fun onBindViewHolder(holder: VH, position: Int) {
holder.item = list[position]
onBindViewHolder(holder, position, holder.item)
}
abstract fun onBindViewHolder(holder: VH, position: Int, item: T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment