Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add endless/infinite scroll to ViewPager2?

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.

like image 459
Ali Yucel Akgul Avatar asked Nov 06 '19 17:11

Ali Yucel Akgul


People also ask

Is infinite scroll good?

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.

How does infinite scrolling work?

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.


1 Answers

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.

like image 155
Da Artagnan Avatar answered Sep 29 '22 17:09

Da Artagnan