Skip to content

Instantly share code, notes, and snippets.

@featzima
Created November 21, 2018 12:01
Show Gist options
  • Save featzima/7fddbdd64738c299754f19990b8f6ace to your computer and use it in GitHub Desktop.
Save featzima/7fddbdd64738c299754f19990b8f6ace to your computer and use it in GitHub Desktop.
class CompositeAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var adapters: List<RecyclerView.Adapter<RecyclerView.ViewHolder>> by adapterProperty(emptyList())
fun addAdapter(adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) {
@Suppress("UNCHECKED_CAST")
adapters = adapters.plus(adapter as RecyclerView.Adapter<RecyclerView.ViewHolder>)
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
notifyDataSetChanged()
}
})
}
override fun getItemCount(): Int {
return adapters.sumBy { it.itemCount }
}
override fun getItemViewType(position: Int): Int {
var currentPosition = position
return adapters.indexOfFirst {
(currentPosition < it.itemCount).apply {
currentPosition -= it.itemCount
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return adapters[viewType].onCreateViewHolder(parent, 0)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
var currentPosition = position
val currentAdapter = adapters.first {
(currentPosition < it.itemCount).apply {
if (!this) currentPosition -= it.itemCount
}
}
currentAdapter.onBindViewHolder(holder, currentPosition)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment