Skip to content

Instantly share code, notes, and snippets.

@louis993546
Created May 14, 2019 23:03
Show Gist options
  • Save louis993546/ad8a484c26880769777df6fea1e6fdf8 to your computer and use it in GitHub Desktop.
Save louis993546/ad8a484c26880769777df6fea1e6fdf8 to your computer and use it in GitHub Desktop.
Using Factory pattern for RecyclerView
class SomeAdapter(
val factory1: ViewHolderFactory1,
val factory2: ViewHOlderFactory2
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemViewType(position: Int) = if (position == 0) 1 else 2
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
1 -> factory1.createViewHolder(parent)
2 -> factory2.createViewHolder(parent)
else -> error("This should not be possible")
}
}
class ViewHolderFactory1 {
fun createViewHolder(parent: ViewGroup) = SomeViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.something, parent, false))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment