Search code examples
androidandroid-viewpager

Getting the current position of a ViewPager


I know with the Gallery widget I was able to use getSelectedItemPosition(); to retrieve the current position, however it doesnt seem ViewPager has that.

I know I can setup a listener and retrieve the position when the page is switched. But I want the current view position.


Solution

  • Create a listener and set it on your viewpager:

    /**
     * Get the current view position from the ViewPager by
     * extending SimpleOnPageChangeListener class and adding your method
     */
    public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
    
        private int currentPage;
    
        @Override
        public void onPageSelected(int position) {
            currentPage = position;
        }
    
        public final int getCurrentPage() {
            return currentPage;
        }
    }