Created
December 13, 2017 07:41
-
-
Save mohanmanu484/42a657d08dc3b8051b776b29cf8efa75 to your computer and use it in GitHub Desktop.
Generic adapter with kotlin
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
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