Search code examples
androidandroid-viewpager

How to get the from position in OnPageChangeListener of a viewpager?


in a viewpager's OnPageChangeListener's onPageSelected you have the current selected position (i.e the current displayed one) How do you get the previous position from which it was scrolled to this current position?


Solution

  • you can get the fromPosition (i.e the position from where the viewpager is being scrolled from in onPageScrolled callback, the position value in this callback method is nothing but the position from which the scroll is being initiated, therefore when onPageSelected is called the position stored from onPageScrolled will be the previous position from which the scroll was started.

    ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
        private int fromPosition = 0;
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            fromPosition = position;
        }
    
        @Override
        public void onPageSelected(int position) {
            Log.v("onPageSelected", "scrolled from position " + fromPosition)
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    }