How to know viewpager is scroll left or right?
- This is my simple solution in the onPageScrolled() method of ViewPager.OnPageChangeListener:
Same solution as GuilhE with a minor fix to avoid getting false positives when paging left (swiping right) on the first page(no more pages to the left) in the ViewPager. It simply does an additional check to see if the swipe has actually moved at all.
new ViewPager.OnPageChangeListener() {
private static final float thresholdOffset = 0.5f;
private static final int thresholdOffsetPixels = 1;
private boolean scrollStarted, checkDirection;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (checkDirection) {
if (thresholdOffset > positionOffset && positionOffsetPixels > thresholdOffsetPixels) {
Log.i(C.TAG, "going left");
} else {
Log.i(C.TAG, "going right");
}
checkDirection = false;
}
}
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrollStateChanged(int state) {
if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
scrollStarted = true;
checkDirection = true;
} else {
scrollStarted = false;
}
}
});
set setOnPageChangeListener
to your ViewPager
keep a variable global as
private int lastPosition = 0;
and in
@Override
public void onPageSelected(int arg0) {
if (lastPosition > position) {
System.out.println("Left");
}else if (lastPosition < position) {
System.out.println("Right");
}
lastPosition = position;
}
It's not a perfect solution but here's a way to check the swipe direction when you start swiping:
new ViewPager.OnPageChangeListener() {
private static final float thresholdOffset = 0.5f;
private boolean scrollStarted, checkDirection;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (checkDirection) {
if (thresholdOffset > positionOffset) {
Log.i(C.TAG, "going left");
} else {
Log.i(C.TAG, "going right");
}
checkDirection = false;
}
}
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrollStateChanged(int state) {
if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
scrollStarted = true;
checkDirection = true;
} else {
scrollStarted = false;
}
}
});
EDIT: there's a more elegant approach that involves using a ViewPager.PageTransformer
and checking it's position intervals:
...
myViewPager.setPageTransformer(true, new PageTransformer());
...
public class PageTransformer implements ViewPager.PageTransformer {
public void transformPage(View view, float position) {
if (position < -1) {
// [-00,-1): the page is way off-screen to the left.
} else if (position <= 1) {
// [-1,1]: the page is "centered"
} else {
// (1,+00]: the page is way off-screen to the right.
}
}
}
You can learn more from: Using ViewPager for Screen Slides