Is there any way to slow the scroll speed with the viewpager adaptor in android?
You know, I've been looking at this code. I can't figure out what I'm dong wrong.
try{
Field mScroller = mPager.getClass().getDeclaredField("mScroller");
mScroller.setAccessible(true);
Scroller scroll = new Scroller(cxt);
Field scrollDuration = scroll.getClass().getDeclaredField("mDuration");
scrollDuration.setAccessible(true);
scrollDuration.set(scroll, 1000);
mScroller.set(mPager, scroll);
}catch (Exception e){
Toast.makeText(cxt, "something happened", Toast.LENGTH_LONG).show();
}
It doesn't change anything yet no exceptions occur?
I've started with HighFlyer's code which indeed changed the mScroller field (which is a great start) but didn't help extend the duration of the scroll because ViewPager explicitly passes the duration to the mScroller when requesting to scroll.
Extending ViewPager didn't work as the important method (smoothScrollTo) can't be overridden.
I ended up fixing this by extending Scroller with this code:
And using it like this:
I've basically hardcoded the duration to 5 seconds and made my ViewPager use it.
Hope this helps.
I've wanted to do myself and have achieved a solution (using reflection, however). It's similar to the accepted solution but uses the same interpolator and only changes the duration based on a factor. You need to use a
ViewPagerCustomDuration
in your XML instead ofViewPager
, and then you can do this:ViewPagerCustomDuration.java
:ScrollerCustomDuration.java
:Hope this helps someone!
This is not perfect solution, you can't make velocity slower because it's an
int
. But for me it's slow enough and I don't have to use reflection.Notice the package where the class is.
smoothScrollTo
has package visibility.Based on accepted solution I have created kotlin class with extension for view pager. Enjoy! :)
The fakeDrag methods on ViewPager seem to provide an alternative solution.
For example this will page from item 0 to 1:
(The
count * count
is just there to make the drag speed up as it goes)As you can see in ViewPager sources, duration of fling controlled by mScroller object. In documantation we may read:
So, if you want to control speed, you may change mScroller object via reflection.
You should write something like this: