Created
November 21, 2018 12:01
-
-
Save featzima/7fddbdd64738c299754f19990b8f6ace to your computer and use it in GitHub Desktop.
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
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