Search code examples
androidandroid-viewpager

Android ViewPager: Scroll to next item only when the previous item is scrolled to 90%


I have a view pager implementation in my app. I want to change its scroll behaviour.

Currently (by default) when we scroll to 50% (almost) of the current item, the view pager scrolls to the next item. I want to change this behaviour. I want that instead of 50%, the next item should come up when the current item is scrolled to 90%. Is it possible to implement this kind of behaviour?


Solution

  • You can make use of :

    pager.addOnPageChangeListener
    

    the solution could be using SimpleOnPageChangeListener method and override it's onPageScrolled method:

         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
    
            @Override
            public void onPageScrolled(int position, float positionOffset,
                    int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (positionOffset> 0.9f){
                    scrolPage()
                }
            }
        }) ;
    

    please take a look into the positionOffset documentation:

    * @param positionOffset Value from [0, 1) indicating the offset from the page at position.