我正在使用一个ViewPager
子类MyPager
(几乎相同),并且我使用它的setCurrentItem(int index, boolean smooth)
方法,将 smooth 参数设置为 true。它实际上比将参数设置为“false”要平滑一些,但我想增加动画持续时间以使过渡更加明显。
我从不同的帖子中收集了一些信息,这个解决方案看起来很完美。我最终得到了这段代码”
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));
}
}
scroller.set(this, mScroller);
问题是,在运行MyPager 行时,我无法摆脱这个异常:
java.lang.IllegalArgumentException: invalid value for field
任何的想法?