For example, I was looking for a looping ViewPager, where on first swiping back from first page takes you to last page, as well on swiping forward on last page takes you back again to the first page and this loop continues.
I checked on stackoverflow for any clean solutions, but I was not satisfied with the hacks detailed over there. I did some brainstorming and started working on my own design.
So, I decided instead of having "n" pages in my ViewPager, I will have "n+2", that is additional 2 pages. I have 2 variables here, position - a zero index based variable specifying page number in ViewPager and contentIndex - an index of string array I am displaying as ViewPager cards. These additional 2 pages would be the first page at position 0 which would display the content at the last index of array, and the last page at position n+1 which would display the content at index 0. Thus for content at index 0 and n are being displayed by 2 pages.
Then I listen for OnPageChange events. For these 2 special pages, as soon as I land on them, instead of displaying these pages, I switch the page to go to the original page that was already displaying it at its proper position. I navigate to it without any animation.
For e.g. if I come to position 0 which displays the last content of array, instead of being at position 0, I switch it to position n which was displaying the same content. The switch is instantaneous, although if you watch closely, you will notice a sort of jerk that happens. Similarly I switch to page at position 1 as soon as I land on page at position n+1.
A project with complete implementation of above hack can be found on Github @anagri/ViewPagerLoop
The screenshots from the above app looks like -
The core logic in code is ->
If you found this helpful or have any suggestions, kindly leave a comment.