The proposed solutions are correct but to achieve the result you need to set the initial value of your viewpager to Integer.MAX_VALUE/2.
Anyway, I don't really like this solution, setting getCount to return Integer.MAX_VALUE can have huge impact on application performance.
I figured out a solution in order to avoid this problem using the:
onPageScrollStateChanged Listener
I simply reorder the fragment list, update the viewPager and move to the new page without animation, the result is an endless loop in both directions:
mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
Boolean first = false;
Boolean last = false;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{}
@Override
public void onPageSelected(int position)
{
if (position == 0)
{
first = true;
last = false;
}
else if (position == mainFragmentList.size() -1)
{
first = false;
last = true;
}
else
{
first = false;
last = false;
}
}
@Override
public void onPageScrollStateChanged(int state)
{
if (first && state == ViewPager.SCROLL_STATE_IDLE)
{
// Jump without animation
Fragment fragment = mainFragmentList.get(mainFragmentList.size() -1);
mainFragmentList.remove(mainFragmentList.size() -1 );
mainFragmentList.add(0,fragment);
mainPagerAdapter.setData(mainFragmentList);
mainPagerAdapter.notifyDataSetChanged();
Log.e(TAG,mainFragmentList.toString());
mainViewPager.setCurrentItem(1,false);
}
if(last && state == ViewPager.SCROLL_STATE_IDLE)
{
// Jump without animation
Fragment fragment = mainFragmentList.get(0);
mainFragmentList.remove(0);
mainFragmentList.add(fragment);
mainPagerAdapter.setData(mainFragmentList);
mainPagerAdapter.notifyDataSetChanged();
Log.e(TAG,mainFragmentList.toString());
mainViewPager.setCurrentItem(mainFragmentList.size()-2,false);
}
}
});
This is what happens here:
in this example, we have 4 fragments A-B-C-D
if the user is on fragment A (first), the new List will become: D-A-B-C
[remove the last and push as first]
I update the ViewPager and move (without animation) again to fragment A so index 1.
Now the user can continue to scroll left and will find fragment D.
Same thing with the last fragment:
starting again with A-B-C-D
if the user is on fragment D (last), the new List will become: B-C-D-A
[remove the first and push as last]
I update the ViewPager and move (without animation) again to fragment D so index mainFragmentList.size()-2.
Now the user can continue to scroll right and will find fragment A.
Remember to implement FragmentStatePagerAdapter NOT FragmentPagerAdapter