I have a ViewPager with some views. I'd like to go to the first one after right swiping on the last one.
I tried
@Override
public Fragment getItem(int arg0) {
int i = arg0 % fragmentList.size();
return fragmentList.get(i);
}
@Override
public int getCount() {
return fragmentList.size()+1;
}
But I got an error
E/AndroidRuntime(22912): java.lang.IllegalStateException: Fragment already added: RubricFragment{4136cd80 #1 id=0x7f06000c android:switcher:2131099660:0}
My solution is based on benkc, but first and last page scroll animation are disabled, and when pages "scrolled" to real page, scroll animation is enable again, this scheme can solve the first drawback.
but my
ViewPager.setCurrentItem(position, false)
result is still have scroll animation, so i implements animation which is too fast to seen.the fast scrolling animation like this, don't mind the comment, just my code didn't use these method:
and use this method to viewpager's activity
and modify onPageScrollStateChanged like this, only first page or last page (i have 5 pages) would change animation to fast scrolling, otherwise has normal scrolling:
FixedSpeedScroller references is here: http://blog.csdn.net/ekeuy/article/details/12841409
this should do the job without dummy pages:
I would create a dummy page at the end of the ViewPager. Then I use this code to go to the first page when the user scroll to the dummy page. I know it's far from perfect :D
this works, the accepted answer no good because there is a lag when the loop happens:
answer taken from here : ViewPager as a circular queue / wrapping
One possibility is setting up the screens like this:
C' A B C A'
C' looks just like C, but when you scroll to there, it switches you to the real C. A' looks just like A, but when you scroll to there, it switches you to the real A.
I would do this by implementing onPageScrollStateChanged like so:
Note that this calls the alternate form of setCurrentItem and passes
false
to cause the jump to happen instantly rather than as a smooth scroll.There are two main drawbacks I see to this. Firstly, upon reaching either end the user has to let the scrolling settle before they can go further. Secondly, it means having a second copy of all of the views in your first and last page. Depending on how resource-heavy your screens are, that may rule out this technique as a possible solution.
Note also that since the view pager doesn't let clicks go through to underlying controls until after the scrolling has settled, it's probably fine to not set up clicklisteners and the like for the A' and C' fragments.
Edit: Having now implemented this myself, there's another pretty major drawback. When it switches from A' to A or C' to C, the screen flickers for a moment, at least on my current test device.