Last active
March 22, 2023 12:43
-
-
Save dmersiyanov/e08b8c94fa3db34988ffc6d285873d32 to your computer and use it in GitHub Desktop.
Handle dynamic ViewPager2 page height
This file contains hidden or 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 Fragment() { | |
private fun initViews() = with(binding) { | |
pager.setPageTransformer { page, pos -> | |
if (pos == 0.0F) { | |
updatePagerHeightForChild(page, pager) | |
} | |
} | |
} | |
} |
This file contains hidden or 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
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