Skip to content

Instantly share code, notes, and snippets.

@mohanmanu484
Created December 13, 2017 07:41
Show Gist options
  • Save mohanmanu484/42a657d08dc3b8051b776b29cf8efa75 to your computer and use it in GitHub Desktop.
Save mohanmanu484/42a657d08dc3b8051b776b29cf8efa75 to your computer and use it in GitHub Desktop.
Generic adapter with kotlin
abstract class GenericAdapter<T> : RecyclerView.Adapter<RecyclerView.ViewHolder> {
var listItems: List<T>
constructor(listItems: List<T>) {
this.listItems = listItems
}
constructor() {
listItems = emptyList()
}
fun setItems(listItems: List<T>) {
this.listItems = listItems
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return getViewHolder(LayoutInflater.from(parent.context)
.inflate(viewType, parent, false)
, viewType)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as Binder<T>).bind(listItems[position])
}
override fun getItemCount(): Int {
return listItems.size
}
override fun getItemViewType(position: Int): Int {
return getLayoutId(position, listItems[position])
}
protected abstract fun getLayoutId(position: Int, obj: T): Int
abstract fun getViewHolder(view: View, viewType: Int):RecyclerView.ViewHolder
internal interface Binder<T> {
fun bind(data: T)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment