由于Viewpager的滑动速度是固定的,所以很蛋疼。看了老外的文章可以利用反射机制,修改Viewpager的滑动速度。下面是代码实现:
需要新建个类FixedSpeedScoller继承自scroller类
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;
/**
* FixedSpeedScroller for controlling sliding animation speed. It uses the java
* reflection mechanism.
*
* @version 1.00 2014.1.6
* @author Huang.xin gkx100120
*
*/
public class FixedSpeedScroller extends Scroller {
private int mDuration = 1500; // default time is 1500ms
public FixedSpeedScroller(Context context) {
super(context);
}
public FixedSpeedScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
/**
* set animation time
*
* @param time
*/
public void setmDuration(int time) {
mDuration = time;
}
/**
* get current animation time
*
* @return
*/
public int getmDuration() {
return mDuration;
}
}
然后需要在初始化Viewpager的地方,加入以下代码:
FixedSpeedScroller mScroller = null;
private void controlViewPagerSpeed() {
try {
Field mField;
mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
mScroller = new FixedSpeedScroller(
mMainHolder.main_viewpager.getContext(),
new AccelerateInterpolator());
mScroller.setmDuration(2000); // 2000ms
mField.set(mMainHolder.main_viewpager, mScroller);
} catch (Exception e) {
e.printStackTrace();
}
}
setmDuration 可以设定想要的时间,这个时间就是滑动的时间。注意上面的mMainHolder.main_viewpager参数,这个是我的viewpager对象,如果大家要用的话,需要修改成自己的viewpager对象。