这个问题已经有了答案:
Change ViewPager animation duration when sliding programmatically
6个答案
我使用的是ViewPager
子类MyPager
(几乎相同),我使用的是它的setCurrentItem(int index, boolean 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
知道吗?
最佳答案
你能修改这部分代码并插入一个日志语句吗?
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
。