Learning Android Development
Breaking barriers of ViewPager 2
Scroll multiple pages, and show more than one items per page

As explains in my previous blog, ViewPager 2 can’t do all that RecyclerView can do. Below are some of it’s limitations
- It can only scroll one page at a time. Can’t scroll multiple pages at a time.
- It can only show a full page of content. Can’t preview the next page content.
However, below are some ways which we could use to break the barrier.
Scrolling multiple pages at a time.
Imagine if you have many pages, scrolling a page at a time is really daunting. Hence would be handy if we can scroll multiple pages at a time.
We could use the fakeDrag to do that, as shown below.

This can be achieved by multiplying the rate of movement as shown below.
private fun handleOnTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
lastValue = event.x
view_pager_quick_scroll.beginFakeDrag()
} MotionEvent.ACTION_MOVE -> {
val value = event.x
val delta = value - lastValue
view_pager_quick_scroll.fakeDragBy(delta * MULTIPLIER)
lastValue = value
} MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
view_pager_quick_scroll.endFakeDrag()
}
}
return true
}Previewing the next page
Even though ViewPager 2 is supposed to show one page at a time, it still would be nice if we can preview the next page (a way to let the user know there’s something to scroll and look at).
This can be achieved by adding additional padding to the RecyclerView within and have clipToPadding = false
view_pager_preview.apply {
offscreenPageLimit = 1
val recyclerView = getChildAt(0) as RecyclerView
recyclerView.apply {
val padding = card_margin + peek_offset_margin
setPadding(padding, 0, padding, 0)
clipToPadding = false
}
adapter = MyAdapterFullLength()
}
The card_margin is the standard margin of the cell, while the peek_offset_margin is how much we like to preview the next page.
Hopes this provide some workaround fitting your need. You can get the sample app here
Updated: To get Bi-directional Infinite Scrolling ViewPager2, checkout the blog below





