android ViewPager自动轮播时控制切换速度

android ViewPager自动轮播时控制切换速度

今天遇到个需求,viewPager要求自动轮播,效果实现了,但是两个View之间切换的速度过快。以下代码可以自定义view切换的速度。
一、新建类
package com.utils;

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

/**
*
*FixedSpeedScroller
*@author tianshi
*@time 2016/11/11 16:58
*/

public class FixedSpeedScroller extends Scroller {
private int mDuration = 1500;

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);
}

public void setmDuration(int time) {
    mDuration = time;
}

public int getmDuration() {
    return mDuration;
}

}


二、在初始化Viewpage位置加上以下代码:
try {
field = ViewPager.class.getDeclaredField(“mScroller”);
field.setAccessible(true);
FixedSpeedScroller scroller = new FixedSpeedScroller(vp01.getContext(), new AccelerateInterpolator());
field.set(vp01, scroller);
//切换速度
scroller.setmDuration(500);
} catch (Exception e) {
e.printStackTrace();
}


OK,大功告成!

你可能感兴趣的:(android)