Android Modify the sliding speed of ViewPager when calling setCurrentItem

1. Foreword:

In the process of using ViewPager, there is a situation where you need to jump directly to a certain page. At this time, you need to use the setCurrentItem method of ViewPager. It means jumping to the specified page of ViewPager, but when using this method There is a problem. There is a sliding effect when jumping. When you need to jump from the current page to other pages, the span of the jump page is too large, or the visual effects of each page of the ViewPager are very different, this method is used to implement the ViewPager. The jump looks very unsightly. What should we do? We can remove the sliding speed when using the setCurrentItem method of ViewPager. The specific implementation is as follows:

import java.lang.reflect.Field;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.animation.Interpolator;
import android.widget.Scroller;

public class ViewPagerScroller extends Scroller{
    
    

    private int mScrollDuration = 800; // 滑动速度

    /**
    * 设置速度速度
    *
    * @param duration
    */
    public void setScrollDuration(int duration) {
    this.mScrollDuration = duration;
    }

    public ViewPagerScroller(Context context) {
    super(context);
    }

    public ViewPagerScroller(Context context, Interpolator interpolator) {
    super(context, interpolator);
    }

    @SuppressLint("NewApi")
    public ViewPagerScroller(Context context, Interpolator interpolator,
    boolean flywheel) {
    super(context, interpolator, flywheel);
    }

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

    public void initViewPagerScroll(ViewPager viewPager) {
    try {
    Field mScroller = ViewPager.class.getDeclaredField("mScroller");
    mScroller.setAccessible(true);
    mScroller.set(viewPager, this);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

}

2 use:

    viewPager.setCurrentItem(showPosition);
        ViewPagerScroller mPagerScroller=new ViewPagerScroller(getActivity());
        mPagerScroller.initViewPagerScroll(viewPager);

3. Take a look at the effect before and after setting:

Before setting up:
Write picture description here

After setting:

Write picture description here

Compare the two sliding effects to see if the visual effect after setting is more comfortable! ! With damping effect, better vision

Guess you like

Origin blog.csdn.net/jky_yihuangxing/article/details/52584787