跳至主要内容

How to change ViewPager scroll animation duration and velocity

When you call change current selected view pager position you may call like this.


// change current position   default is viewPager.setCurrentItem(position, true);
viewPager.setCurrentItem(position);

There will show transaction animation for change position , but this animation is too fast. So I want change this animation.

When I see source code I find this, like flow. where is the scroll animation and speed.


    int duration = 0;
    velocity = Math.abs(velocity);
    if (velocity > 0) {
        duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
    } else {
        final float pageWidth = width * mAdapter.getPageWidth(mCurItem);
        final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);
        duration = (int) ((pageDelta + 1) * 100);
    }
    duration = Math.min(duration, MAX_SETTLE_DURATION);

    mScroller.startScroll(sx, sy, dx, dy, duration);
But there no API for change this mScroller in API8 level. Then I want to change this with reflect, write my Custom Scroller in ViewPager.


/**
 * Created by Jerry on 14-6-6.
 */
public class ViewPagerScroller extends Scroller {
private int mScrollDuration = 600;// 滑动速度
public ViewPagerScroller(Context context) {
    super(context);
}
public ViewPagerScroller(Context context, Interpolator interpolator) {
    super(context, interpolator);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
    super.startScroll(startX, startY, dx, dy, mScrollDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
    super.startScroll(startX, startY, dx, dy, mScrollDuration);
}
}

Then last step is set this Scroller into my ViewPager like this.


private void changePagerScroller() {
    try {
        Field mScroller = null;
        mScroller = ViewPager.class.getDeclaredField("mScroller");
        mScroller.setAccessible(true);
        ViewPagerScroller scroller = new ViewPagerScroller(viewPager.getContext());
        mScroller.set(viewPager, scroller);
    } catch (Exception e) {
        Log.e(TAG, "error of change scroller ", e);
    }
}

Now it work.

评论

发表评论