我正在使用ViewPager
子类MyPager
(几乎相同),我使用其setCurrentItem(int index, boolean smooth)
方法,并将smooth参数设置为true。它实际上比参数设置为'false'更平滑,但我想增加动画持续时间以使转换更加明显。
我收集了来自不同帖子的一些信息,this solution看起来很完美。我最终得到了这段代码“
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));
}
}
问题是,当我通过MyPager的scroller.set(this, mScroller);
行时,我无法摆脱这个异常:
java.lang.IllegalArgumentException: invalid value for field
有什么想法吗?
答案 0 :(得分:6)
您可以修改这部分代码并插入Log语句吗?
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));
Log.d("TAG", "mScroller is: " + mScroller + ", "
+ mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is "
+ this + ", " + getClass().getSuperclass().getCanonicalName());
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}
然后发布输出?
编辑:问题是导入语句不正确。 mScroller
是android.widget.Scroller
,您无法为其分配com.WazaBe.HoloEverywhere.widget.Scroller
。