This question already has an answer here:
- Change ViewPager animation duration when sliding programmatically 6 answers
I'm using a ViewPager
subclass MyPager
(which is almost the same), and I use its setCurrentItem(int index, boolean smooth)
method, with the smooth parameter set to true. It's actually a little smoother than with parameter set to 'false', but I'd like to increase the animation duration to make the transition more visible.
I have gathered some information from different posts and this solution looks perfect. I've ended up with this code"
MyPager.java :
public class MyPager extends ViewPager {
public MyPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
postInitViewPager();
}
private ScrollerCustomDuration mScroller = null;
/**
* Override the Scroller instance with our own class so we can change the
* duration
*/
private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}
}
/**
* Set the factor by which the duration will change
*/
public void setScrollDurationFactor(double scrollFactor) {
mScroller.setScrollDurationFactor(scrollFactor);
}
}
ScrollerCustomDuration.java
public class ScrollerCustomDuration extends Scroller {
private double mScrollFactor = 2;
public ScrollerCustomDuration(Context context) {
super(context);
}
public ScrollerCustomDuration(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public ScrollerCustomDuration(Context context,
Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
/**
* Set the factor by which the duration will change
*/
public void setScrollDurationFactor(double scrollFactor) {
mScrollFactor = scrollFactor;
}
@Override
public void startScroll(int startX, int startY, int dx, int dy,
int duration) {
super.startScroll(startX, startY, dx, dy,
(int) (duration * mScrollFactor));
}
}
The thing is, I can't get rid of this exception, when running through the line scroller.set(this, mScroller);
of MyPager :
java.lang.IllegalArgumentException: invalid value for field
Any idea?