Skip to content

Instantly share code, notes, and snippets.

@dmersiyanov
Last active March 22, 2023 12:43
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 dmersiyanov/e08b8c94fa3db34988ffc6d285873d32 to your computer and use it in GitHub Desktop.
Save dmersiyanov/e08b8c94fa3db34988ffc6d285873d32 to your computer and use it in GitHub Desktop.
Handle dynamic ViewPager2 page height
class Fragment() {
private fun initViews() = with(binding) {
pager.setPageTransformer { page, pos ->
if (pos == 0.0F) {
updatePagerHeightForChild(page, pager)
}
}
}
}
import android.graphics.Rect
import android.view.View
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import androidx.viewpager2.widget.ViewPager2
fun updatePagerHeightForChild(view: View, pager: ViewPager2) {
view.post {
val wMeasureSpec = View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
view.measure(wMeasureSpec, hMeasureSpec)
view.doOnLayout {
val pageVisibleRect = Rect().also {
view.getGlobalVisibleRect(it)
}
val pageVisibleHeight = pageVisibleRect.height()
val pageActualHeight = view.measuredHeight
val pagerVisibleRect = Rect().also {
pager.getGlobalVisibleRect(it)
}
val pagerVisibleHeight = pagerVisibleRect.height()
val rootVisibleRect = Rect().also {
pager.rootView.getGlobalVisibleRect(it)
}
val rootVisibleHeight = rootVisibleRect.height()
val isPageSmallerThanAvailableHeight =
pageActualHeight <= pageVisibleHeight && pagerVisibleHeight <= rootVisibleHeight
if (isPageSmallerThanAvailableHeight) {
pager.updateLayoutParams {
height = pagerVisibleRect.bottom - pageVisibleRect.top
}
} else {
pager.updateLayoutParams {
height = pageActualHeight
}
}
pager.invalidate()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment