there is no method for overscroll in ViewPager2
I need to detect the overscroll so I can take the user back to home page once there are no more pages.
Detect overscroll or end of pages event in ViewPager2 android
1.7k views Asked by Rahul Tiwari At
2
There are 2 answers
0
On
I think it's a clearer and cleaner solution.
private fun viewPagerScrollStateListener() {
binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
private var scrolling = false
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
scrolling = when (state) {
ViewPager2.SCROLL_STATE_DRAGGING -> true
ViewPager2.SCROLL_STATE_SETTLING -> true
ViewPager2.SCROLL_STATE_IDLE -> {
if (scrolling && isLastPage()) {
// Scrolling has ended and we are on the last page
onEndScroll()
}
false
}
else -> false
}
}
private fun isLastPage(): Boolean {
return binding.viewPager.currentItem + 1 == adapter.itemCount
}
private fun onEndScroll() {
Log.i("ViewPager", "End of scrolling")
}
})
}
ViewPager2 does not have a public method for over scroll, however, It can be detected by listening to
onPageScrollStateChanged
Usually transition of events in
onPageScrollStateChanged
for scroll state isSCROLL_STATE_DRAGGING
->SCROLL_STATE_SETTLING
->SCROLL_STATE_IDLE
when changing a pageBut in case of overscroll the sequence is
SCROLL_STATE_DRAGGING
->SCROLL_STATE_IDLE