ViewPager设置切换动画

在原生的ViewPager切换时会显的很突然很生硬,百度了许多前辈的案例,思路都差不多,那就是先写一个继承Scroller的类SpeedScroller


package com.youhe.yoyo.addforlu;

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

/**
 * Created by abc on 2016/12/1.
 */

public class SpeedScroller extends Scroller {
    private int mDuration = 1000;

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

    public SpeedScroller(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;
    }

}


这个类写好之后就可以直接引用了,在需要用到的Activity里:

mypager = (ViewPager) parentView.findViewById(R.id.News_pager);
        mypager.setPageTransformer(true, new ZoomOutPageTransformer());
        pagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), imageList,context);
        mypager.setAdapter(pagerAdapter);

        SpeedScroller mScroller;
        try {
            Field mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);
            mScroller = new SpeedScroller(mypager.getContext(),new LinearInterpolator());
            mField.set(mypager, mScroller);
            mScroller.setmDuration(500);//ms
        } catch (Exception e) {
            e.printStackTrace();
        }

首先绑定组件,然后设置动画(下面将给出7种不同的动画风格)
mypager.setPageTransformer(true, new ZoomOutPageTransformer());
注意这句:
mScroller = new SpeedScroller(mypager.getContext(),new LinearInterpolator());


SpeedScroller方法里的第二个参数是插值器,我们也有很多种
AccelerateDecelerateInterpolator   在动画开始与介绍的地方速率改变比较慢,在中间的时候加速
AccelerateInterpolator                     在动画开始的地方速率改变比较慢,然后开始加速
AnticipateInterpolator                      开始的时候向后然后向
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值