用按钮的点击事件切换ViewPager到某一个子页面,我们一般使用
mViewPager.setCurrentItem(positon),这时你会发现ViewPager快速的闪到你所设置的页面,如果我们要控制这个切换过程有个过渡效果,该怎么办呢
自定义一个Scroller类,控制ViewPager的滑动速度
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;
public class SpeedScroller extends Scroller {
private int mDuration = 300;
public SpeedScroller(Context context) {
super(context);
}
public SpeedScroller(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);
}
public void setmDuration(int time) {
mDuration = time;
}
public int getmDuration() {
return mDuration;
}
}
通过反射机制设置ViewPager的滑动速度
ViewPager mViewPager= (ViewPager) findViewById(R.id.mViewPager);
try {
<span style="white-space:pre"> </span>Field mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
SpeedScroller mScroller =new SpeedScroller
(mViewPager.getContext(),new AccelerateInterpolator());
mField.set(mViewPager,mScroller);
} catch (Exception e) {
<span style="white-space:pre"> </span>e.printStackTrace();
}