Infinite Scrolling Horizontally of ViewPager or UICollectionView

Before development, I would strongly recommend to read this blog first, which introduce the concept about how creating an infinite scrolling UICollectionView horizontally. It’s for iOS engineer, but we can implement its concept into both Android and iOS.

The scenarios is adding 2 more items into viewpager: one is duplicated first item on original list which adding to the tail, the other is duplicated last one which adding on the head. For example, let’s define original items, [A, B, C], and we extend the items to [C’, A, B, C, A’].

And then, when users scroll to A’, ViewPager will jump to A without animation, likewise, when scrolling to C’, Viewpager will jump to C directly.


Here what I did is to implement this concept on android with ViewPager and PagerAdapter: One is CyclerPagerAdapter and the other is CyclerViewPager,

CyclePagerAdapter

CyclerPagerAdater extends PagerAdapter, its major job is to enlarge original item list (with 2 more items, C’ and A’), and jump from fake item (C’ or A’) into actual item (C’ to C, or A’ to A). It’s easy to add 2 duplicated items into original item list, I did in constructor.

Then it add OnPageChangeListener in its corresponding Viewpager, cyclerViewPager. This is because we need to scroll without animation when user scrolls to first page and last one.

CycleViewPager

CycleViewPager extends ViewPager, we need to override original setAdapter because original setAdapter will display 1st page (however, the 1st page is fake C’, so it will display the original A). After calling super.setAdapter(), we shall use setCurrentItem(1, false) to scroll into 2nd one, A, without animation.