I have a FragmentStateAdapter that is attached to new ViewPager2. In the previous ViewPager implementation there were number of ways to implement endless/infinite scroll. How to do so in ViewPager2?
Thanks in advance.
Infinite scroll is great for touchscreens and especially for mobile devices. A user can easily swipe down to keep generating new content instead of switching to new tabs, which can feel cumbersome.
Infinite scrolling is a listing-page design approach which loads content continuously as the user scrolls down. It eliminates the need for pagination — breaking content up into multiple pages.
This is what I came up with:
class EndlessScrollAdapter internal constructor(
fm: FragmentManager,
lifeCycle: Lifecycle
) : FragmentStateAdapter(fm, lifeCycle) {
private val items = mutableListOf<YourModel>()
val firstElementPosition = Int.MAX_VALUE / 2
fun updateList(list: List<YourModel>) {
items.apply {
clear()
addAll(list)
}
notifyDataSetChanged()
}
override fun getItemCount(): Int = if (items.isNotEmpty()) Int.MAX_VALUE else 0
override fun createFragment(position: Int): Fragment = YourPagerFragment(
items[position.rem(items.size)])
}
In Activity or Fragment we need to call:
viewPager2.adapter = endlessScrollAdapter
endlessScrollAdapter.apply {
updateList(yourModelList)
viewPager2.setCurrentItem(this.firstElementPosition, false)
}
Literally it's not endless but from the user perspective it is, as he will never reach to the edge. The lenght of ViewPager2 is Int.MAX_VALUE
, the start position is Int.MAX_VALUE/2
so user can scroll foward and backwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With