android SnapHelper(RecyclerView)
2018-07-18 本文已影响64人
yunhen
参考文章https://blog.csdn.net/poorkick/article/details/77998374
详细文章https://www.jianshu.com/p/e54db232df62
SnapHelper
可以看出SnapHelper是对RecyclerView的一种拓展功能,支持snapping。SnapHelper通过处理RecyclerView的fling,来达到要展示的效果,但是这需要一个前提条件,就是RecyclerView的LayoutManager必须实现ScrollVectorProvider接口或者手动实现onFling接口,自己实现fling处理。
SnapHelper的实现原理是监听RecyclerView.OnFlingListener中的onFling接口。LinearSnapHelper&PagerSnapHelper是抽象类SnapHelper的具体实现。
区别在于:
LinerSnapHelper,可滑动多页,居中显示;
PagerSnapHelper,每次只能滑动一页,居中显示;
一般步骤:
- 创建SnapHelper;
- attachToRecyclerView。
LinerSnapHelper基本使用
横向
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
CardAdapter cardAdapter = new CardAdapter(this);
LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
mRvContent.setLayoutManager(llm);
mRvContent.setAdapter(cardAdapter);
linearSnapHelper.attachToRecyclerView(mRvContent);
纵向
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
CardAdapter cardAdapter = new CardAdapter(this);
LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
mRvContent.setLayoutManager(llm);
mRvContent.setAdapter(cardAdapter);
linearSnapHelper.attachToRecyclerView(mRvContent);
PagerSnapHelper基本使用
横向
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
CardAdapter cardAdapter = new CardAdapter(this);
PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
mRvContent.setLayoutManager(llm);
mRvContent.setAdapter(cardAdapter);
pagerSnapHelper.attachToRecyclerView(mRvContent);
onFling(抛动)
Fling操作:
手指在屏幕上滑动RecyclerView后松手,RecyclerView中的内容会靠着惯性继续往之前滑动的方向继续滚动直到停止,这个过程叫做Fling。Fling操作从手指离开屏幕瞬间被触发,在滚动停止时结束。
开源demoRecyclerViewSnap