您的位置:首页 > 其它

Viewpager切换滑动速度的修改

2015-12-30 11:29 435 查看
默认情况下,viewpager的setcurrentItem()方法的切换时间是写死的

我们要想修改他的滑动时间,需要引入新的类继承Scroller

具体代码如下:

import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;


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的地方进行设置滑动时间,调用下面的方法就可以

private void controlViewPagerSpeed(){
try {
Field mField;
FixedSpeedScroller mScroller = null;
mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);

mScroller = new FixedSpeedScroller(
viewPager.getContext(),
new AccelerateInterpolator());
mScroller.setmDuration(200); // 2000ms
mField.set(viewPager, mScroller);
} catch (Exception e) {
e.printStackTrace();
}
}

其中 setmDuration()中的时间就是我们需要设置的切换时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: