PagerSnapHelper,官方解释,PagerSnapHelper can help achieve a similar behavior to ViewPager.,就是让RecyclerView能像ViewPager一样工作。
PageSnapHelper衍生于SnapHepler,SnapHepler是什么?从代码可以看出该组件本质上就是一个RecyclerView.OnFlingListener
public abstract class SnapHelper extends RecyclerView.OnFlingListener
SnapHepler类是个抽象类,有两个实现类LinearSnapHelper和PagerSnapHelper。
使用时两行代码就能搞定了,
PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
pagerSnapHelper.attachToRecyclerView(recyclerView);
如果想知道当前页是第几页,可以监听滚动
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {//如果滚动结束
View snapView = scrollHelper.findSnapView(layoutManager);
if (layoutManager != null && snapView != null) {
int currentPageIndex = layoutManager.getPosition(snapView);
if (currentPostion != currentPageIndex) {//防止重复提示
currentPostion = currentPageIndex;
Logger.e("当前是第" + currentPageIndex + "页");
}
}
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
/***如需要灵敏的获取到位置,可在此处进行处理*/
View snapView = scrollHelper.findSnapView(layoutManager);
if (layoutManager != null && snapView != null) {
int currentPageIndex = layoutManager.getPosition(snapView);
if (currentPostion != currentPageIndex) { //防止重复提示
currentPostion = currentPageIndex;
Logger.e("当前是第" + currentPageIndex + "页");
}
}
}
});
为了知道当前页是第几页走了一些弯路,实际中发现,从RecyclerView的postion是无法获取到准确值的。很大可能会出现当前显示的第一页(index=0),但从RecyclerView获取到的postion至少大于等于1,一直怀疑是自己的获取postion方法错误,搞的心力交瘁,这里记录一下获取RecyclerView的position的位置的方法
1、使用接口回调,回调写在onBindViewHolder方法下,回调postion的位置
2、写在ViewHolder里面,处理按钮点击事件,事件中处理postion回调
同时获取postion的方法用两个,getAdapterPosition()和getLayoutPosition
getAdapterPostion()得到的返回值为NO_POSITION(-1),在使用这个结果的时候,可能需要做异常处理,否则可能会出现ArrayIndexOutOfBoundsException的异常。
通过getLayoutPosition()获取的位置信息,是更新布局之前的位置信息,所以通过getLayoutPosition获取的结果有可能是脏数据。
本文深入解析PagerSnapHelper,一种使RecyclerView具备类似ViewPager滑动效果的工具。介绍其原理,包括SnapHelper类及其实现,以及如何在项目中快速应用并监听当前页面变化。
1737





