android material design:recyclerview + snaphelper实现炫酷viewpager效果

目录

什么是SnapHelper

SnapHelper是Google 在 Android 24.2.0 的support 包中添加的对RecyclerView的拓展,结合RecyclerView使用,能很方便的做出一些炫酷的效果。

SnapHelper的使用方法

SnapHelper是一个抽象类 Google 内置了两个默认实现类,LinearSnapHelper和PagerSnapHelper。

  • LinearSnapHelper:使当前Item居中显示,常用场景是横向的RecyclerView, 类似ViewPager效果,但是又可以快速滑动多个条目。
    1
    2
    3
    4
    5
    LinearLayoutManager manager = new LinearLayoutManager(getContext());
    manager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(manager);
    LinearSnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(mRecyclerView);
  • PagerSnapHelper:使RecyclerView 像ViewPager一样的效果,每次只能滑动一页。
    1
    2
    3
    4
    5
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    mRecycleview.setLayoutManager(linearLayoutManager);
    PagerSnapHelper snapHelper = new PagerSnapHelper();
    snapHelper.attachToRecyclerView(mRecycleview);

这里我只使用了PagerSnapHelper做了一个案例:

项目源码:
https://github.com/myml666/SnapHelperDemo