I am using ViewPager (support library). I want to know every time the ViewPager change the visible page, it is scrolling left or right.
Please give me a solution. Any recommend is welcome also.
Thanks
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
To enable / disable the swiping, just overide two methods: onTouchEvent and onInterceptTouchEvent . Both will return "false" if the paging was disabled. You just need to call the setPagingEnabled method with false and users won't be able to swipe to paginate.
Android ViewPager widget is found in the support library and it allows the user to swipe left or right to see an entirely new screen. Today we're implementing a ViewPager by using Views and PagerAdapter. Though we can implement the same using Fragments too, but we'll discuss that in a later tutorial.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With