首先使用 TimerTask 创建 Slider 类扩展
public class SliderTimer extends TimerTask {
private ViewPager viewPager;
private int size;
private Activity activity;
public SliderTimer(ViewPager viewPager, int size, Activity activity) {
this.viewPager = viewPager;
this.size = size;
this.activity = activity;
}
@Override
public void run() {
activity.runOnUiThread(() -> {
if (viewPager.getCurrentItem() < size - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
} else {
viewPager.setCurrentItem(0, true);
}
});
}
}
Next 创建 SpeedSlowScroller 用于慢速滚动
public class SpeedSlowScroller extends Scroller {
private int mDuration = 2500;
public SpeedSlowScroller(Context context) {
super(context);
}
public SpeedSlowScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public SpeedSlowScroller(Context context, Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
@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);
}
}
最后将SpeedSlowScroller添加到 ViewPager 中,并添加SliderTimer用于自动滚动
try {
Field mScroller = ViewPager.class.getDeclaredField("mScroller");
mScroller.setAccessible(true);
SpeedSlowScroller scroller = new SpeedSlowScroller(_context);
mScroller.set(your_viewpager, scroller);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(your_viewpager, models.size(), activity), 4000, 6000);
} catch (Exception ignored) {
}