Android中ViewPager如何改变滑动的动画时间

在默认的ViewPager中,我们左右滑动屏幕会有一个动画,这个动画的的速度,是不能改变的。

可以通过如下方法搞定:

package com.coder4.viewpagerdemo;

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

/**
 * Created by coder4 on 16/3/4.
 */
public class FixedSpeedScroller extends Scroller {

    private int mDuration = 300;

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

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

    public FixedSpeedScroller(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);
    }
}
然后通过反射改一下ViewPager,如下:

try {  
            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(getContext(), new LinearInterpolator());
            // scroller.setFixedDuration(5000);
            mScroller.set(viewPager, scroller);
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }

 

Leave a Reply

Your email address will not be published. Required fields are marked *