控制ViewPager的切换速度
第一步:首先创建一个类继承Scroller
package com.front.adshow; import android.content.Context; import android.view.animation.Interpolator; import android.widget.Scroller; public class FixedSpeedScroller extends Scroller { private int mDuration = 1000; public FixedSpeedScroller(Context context) { super(context); // TODO Auto-generated constructor stub } 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; } }
第二步:在使用ViewPager的Activity中
viewPager = (ViewPager) findViewById(R.id.vp); adapter = new MyPagerAdapter(); viewPager.setAdapter(adapter); try { Field mField = ViewPager.class.getDeclaredField("mScroller"); mField.setAccessible(true); mScroller = new FixedSpeedScroller(viewPager.getContext(),new AccelerateInterpolator()); mField.set(viewPager, mScroller); } catch (Exception e) { e.printStackTrace(); }
第三步:在控制ViewPager切换图片时,加入以下代码即可
viewPager.setCurrentItem(currentItem); mScroller.setmDuration(2* 1000);
注意:2*1000表示切换过程是2秒,可以随意设置