Skip to content

Instantly share code, notes, and snippets.

@rcd27
Created April 19, 2021 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcd27/30620b5ae0946de90fdafffa7043504d to your computer and use it in GitHub Desktop.
Save rcd27/30620b5ae0946de90fdafffa7043504d to your computer and use it in GitHub Desktop.
A workaround for Android ViewPager2 bug with its `height`
/**
* This hacky class is needed because ViewPager2 still has some troubles in
* calculating HEIGHT for its tabs
* see: https://issuetracker.google.com/issues/133135685
*/
abstract class ViewPager2Adapter<T>(tabCount: Int) :
ListAdapter<T, RecyclerView.ViewHolder>(object : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
// We suppose that we show the same objects for every tab
return true
}
// Suppress this warning here because we "remember" to pass `data class` which implements
// `equals()` method, do we?
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
return oldItem == newItem
}
}) {
private val tabs: MutableList<Int> = MutableList(tabCount) { 0 }
@CallSuper
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
Handler().post {
tabs[position] = holder.itemView.height
holder.itemView.minimumHeight = tabs.max()!! // Should be fine since tabCount != null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment