1.简介
RecyclerView在24.2.0版本中新增了SnapHelper这个辅助类,用于辅助RecyclerView在滚动结束时将Item对齐到某个位置。特别是列表横向滑动时,很多时候不会让列表滑到任意位置,而是会有一定的规则限制,这时候就可以通过SnapHelper来定义对齐规则了。
SnapHelper是一个抽象类,官方提供了一个LinearSnapHelper的子类,可以让RecyclerView滚动停止时相应的Item停留中间位置。25.1.0版本中官方又提供了一个PagerSnapHelper的子类,可以使RecyclerView像ViewPager一样的效果,一次只能滑一页,而且居中显示。
这两个子类使用方式也很简单,只需要创建对象之后调用attachToRecyclerView()
附着到对应的RecyclerView对象上就可以了。
new LinearSnapHelper().attachToRecyclerView(mRecyclerView);
//或者
new PagerSnapHelper().attachToRecyclerView(mRecyclerView);
2.原理
2.1 Fling操作
首先来了解一个概念,手指在屏幕上滑动RecyclerView然后松手,RecyclerView中的内容会顺着惯性继续往手指滑动的方向继续滚动直到停止,这个过程叫做Fling。Fling操作从手指离开屏幕瞬间被触发,在滚动停止时结束。
2.2 三个抽象方法
1.
public abstract int findTargetSnapPosition(LayoutManager layoutManager, int velocityX, int velocityY)
该方法会根据触发Fling操作的速率(参数velocityX和参数velocityY)来找到RecyclerView需要滚动到哪个位置,该位置对应的ItemView就是那个需要进行对齐的列表项。我们把这个位置称为targetSnapPosition,对应的View称为targetSnapView。如果找不到targetSnapPosition,就返回RecyclerView.NO_POSITION。
2.
public abstract View findSnapView(LayoutManager layoutManager)
该方法会找到当前layoutManager上最接近对齐位置的那个view,该view称为SanpView,对应的position称为SnapPosition。如果返回null,就表示没有需要对齐的View,也就不会做滚动对齐调整。
3.
public abstract int[] calculateDistanceToFinalSnap(@NonNull LayoutManager layoutManager, @NonNull View targetView);
这个方法会计算第二个参数对应的ItemView当前的坐标与需要对齐的坐标之间的距离。该方法返回一个大小为2的int数组,分别对应x轴和y轴方向上的距离。
attachToRecyclerView():
SnapHelper正是通过该方法附着到RecyclerView上,从而实现辅助RecyclerView滚动对齐操作。源码如下:
public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
throws IllegalStateException {
//如果SnapHelper之前已经附着到此RecyclerView上,不用进行任何操作
if (mRecyclerView == recyclerView) {
return;
}
//如果SnapHelper之前附着的RecyclerView和现在的不一致,清理掉之前RecyclerView的回调
if (mRecyclerView != null) {
destroyCallbacks();
}
//更新RecyclerView对象引用
mRecyclerView = recyclerView;
if (mRecyclerView != null) {
//设置当前RecyclerView对象的回调
setupCallbacks();
//创建一个Scroller对象,用于辅助计算fling的总距离,后面会涉及到
mGravityScroller = new Scroller(mRecyclerView.getContext(),
new DecelerateInterpolator());
//调用snapToTargetExistingView()方法以实现对SnapView的对齐滚动处理
snapToTargetExistingView();
}
}
snapToTargetExistingView():
void snapToTargetExistingView() {
if (mRecyclerView == null) {
return;
}
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager == null) {
return;
}
//找出SnapView
View snapView = findSnapView(layoutManager);
if (snapView == null) {
return;
}
//计算出SnapView需要滚动的距离
int[] snapDistance = calculateDistanceToFinalSnap(layoutManager, snapView);
//如果需要滚动的距离不是为0,就调用smoothScrollBy()使RecyclerView滚动相应的距离
if (snapDistance[0] != 0 || snapDistance[1] != 0) {
mRecyclerView.smoothScrollBy(snapDistance[0], snapDistance[1]);
}
}
可以看到,snapToTargetExistingView()
方法就是先找到SnapView,然后计算SnapView当前坐标到目的坐标之间的距离,然后调用RecyclerView.smoothScrollBy()
方法实现对RecyclerView内容的平滑滚动,从而将SnapView移到目标位置,达到对齐效果。RecyclerView.smoothScrollBy()
这个方法的实现原理这里就不展开了 ,它的作用就是根据参数平滑滚动RecyclerView的中的ItemView相应的距离。
2.3 LinearSnapHelper
LinearSnapHelper 默认居中对齐,看看内部实现过程
SnapHelper辅助RecyclerView滚动对齐的框架已经搭好了,子类只要根据对齐方式实现那三个抽象方法就可以了。
calculateDistanceToFinalSnap():
@Override
public int[] calculateDistanceToFinalSnap(
@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) {
int[] out = new int[2];
//水平方向滚动,则计算水平方向需要滚动的距离,否则水平方向的滚动距离为0
if (layoutManager.canScrollHorizontally()) {
out[0] = distanceToCenter(layoutManager, targetView,
getHorizontalHelper(layoutManager));
} else {
out[0] = 0;
}
//竖直方向滚动,则计算竖直方向需要滚动的距离,否则水平方向的滚动距离为0
if (layoutManager.canScrollVertically()) {
out[1] = distanceToCenter(layoutManager, targetView,
getVerticalHelper(layoutManager));
} else {
out[1] = 0;
}
return out;
}
private int distanceToCenter(@NonNull RecyclerView.LayoutManager layoutManager,
@NonNull View targetView, OrientationHelper helper) {
//找到targetView的中心坐标
final int childCenter = helper.getDecoratedStart(targetView) +
(helper.getDecoratedMeasurement(targetView) / 2);
final int containerCenter;
//找到容器(RecyclerView)的中心坐标
if (layoutManager.getClipToPadding()) {
containerCenter = helper.getStartAfterPadding() + helper.getTotalSpace() / 2;
} else {
containerCenter = helper.getEnd() / 2;
}
//两个中心坐标的差值就是targetView需要滚动的距离
return childCenter - containerCenter;
}
findSnapView():
@Override
public View findSnapView(RecyclerView.LayoutManager layoutManager) {
if (layoutManager.canScrollVertically()) {
return findCenterView(layoutManager, getVerticalHelper(layoutManager));
} else if (layoutManager.canScrollHorizontally()) {
return findCenterView(layoutManager, getHorizontalHelper(layoutManager));
}
return null;
}
寻找SnapView,这里的目的坐标就是RecyclerView中间位置坐标,可以看到会根据layoutManager的布局方式(水平布局方式或者竖向布局方式)区分计算,但最终都是通过findCenterView()
方法来找snapView的。
private View findCenterView(RecyclerView.LayoutManager layoutManager,
OrientationHelper helper) {
int childCount = layoutManager.getChildCount();
if (childCount == 0) {
return null;
}
View closestChild = null;
//找到RecyclerView的中心坐标
final int center;
if (layoutManager.getClipToPadding()) {
center = helper.getStartAfterPadding() + helper.getTotalSpace() / 2;
} else {
center = helper.getEnd() / 2;
}
int absClosest = Integer.MAX_VALUE;
//遍历当前layoutManager中所有的ItemView
for (int i = 0; i < childCount; i++) {
final View child = layoutManager.getChildAt(i);
//ItemView的中心坐标
int childCenter = helper.getDecoratedStart(child) +
(helper.getDecoratedMeasurement(child) / 2);
//计算此ItemView与RecyclerView中心坐标的距离
int absDistance = Math.abs(childCenter - center);
//对比每个ItemView距离到RecyclerView中心点的距离,找到那个最靠近中心的ItemView然后返回
if (absDistance < absClosest) {
absClosest = absDistance;
closestChild = child;
}
}
return closestChild;
}
findTargetSnapPosition():
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX,
int velocityY) {
//判断layoutManager是否实现了RecyclerView.SmoothScroller.ScrollVectorProvider这个接口
if (!(layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider)) {
return RecyclerView.NO_POSITION;
}
final int itemCount = layoutManager.getItemCount();
if (itemCount == 0) {
return RecyclerView.NO_POSITION;
}
//找到snapView
final View currentView = findSnapView(layoutManager);
if (currentView == null) {
return RecyclerView.NO_POSITION;
}
final int currentPosition = layoutManager.getPosition(currentView);
if (currentPosition == RecyclerView.NO_POSITION) {
return RecyclerView.NO_POSITION;
}
RecyclerView.SmoothScroller.ScrollVectorProvider vectorProvider =
(RecyclerView.SmoothScroller.ScrollVectorProvider) layoutManager;
// 通过ScrollVectorProvider接口中的computeScrollVectorForPosition()方法
// 来确定layoutManager的布局方向
PointF vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1);
if (vectorForEnd == null) {
return RecyclerView.NO_POSITION;
}
int vDeltaJump, hDeltaJump;
if (layoutManager.canScrollHorizontally()) {
//layoutManager是横向布局,并且内容超出一屏,canScrollHorizontally()才返回true
//估算fling结束时相对于当前snapView位置的横向位置偏移量
hDeltaJump = estimateNextPositionDiffForFling(layoutManager,
getHorizontalHelper(layoutManager), velocityX, 0);
//vectorForEnd.x < 0代表layoutManager是反向布局的,就把偏移量取反
if (vectorForEnd.x < 0) {
hDeltaJump = -hDeltaJump;
}
} else {
//不能横向滚动,横向位置偏移量当然就为0
hDeltaJump = 0;
}
//竖向的原理同上
if (layoutManager.canScrollVertically()) {
vDeltaJump = estimateNextPositionDiffForFling(layoutManager,
getVerticalHelper(layoutManager), 0, velocityY);
if (vectorForEnd.y < 0) {
vDeltaJump = -vDeltaJump;
}
} else {
vDeltaJump = 0;
}
//根据layoutManager的横竖向布局方式,最终横向位置偏移量和竖向位置偏移量二选一,作为fling的位置偏移量
int deltaJump = layoutManager.canScrollVertically() ? vDeltaJump : hDeltaJump;
if (deltaJump == 0) {
return RecyclerView.NO_POSITION;
}
//当前位置加上偏移位置,就得到fling结束时的位置,这个位置就是targetPosition
int targetPos = currentPosition + deltaJump;
if (targetPos < 0) {
targetPos = 0;
}
if (targetPos >= itemCount) {
targetPos = itemCount - 1;
}
return targetPos;
}
RecyclerView的layoutManager很灵活,有两种布局方式(横向布局和纵向布局),每种布局方式有两种布局方向(正向布局和反向布局)。这个方法在计算targetPosition的时候把布局方式和布局方向都考虑进去了。布局方式可以通过layoutManager.canScrollHorizontally()
/layoutManager.canScrollVertically()
来判断,布局方向就通过RecyclerView.SmoothScroller.ScrollVectorProvider
这个接口中的computeScrollVectorForPosition()
方法来判断。
所以SnapHelper为了适配layoutManager的各种情况,特意要求只有实现了RecyclerView.SmoothScroller.ScrollVectorProvider
接口的layoutManager才能使用SnapHelper进行辅助滚动对齐。官方提供的LinearLayoutManager、GridLayoutManager和StaggeredGridLayoutManager都实现了这个接口,所以都支持SnapHelper。
这几个方法在计算位置的时候用的是OrientationHelper这个工具类,它是LayoutManager用于测量child的一个辅助类,可以根据Layoutmanager的布局方式和布局方向来计算得到ItemView的大小位置等信息。
从源码中可以看到findTargetSnapPosition()
会先找到fling操作被触发时界面上的snapView(因为findTargetSnapPosition()
方法是在onFling()
方法中被调用的),得到对应的snapPosition,然后通过estimateNextPositionDiffForFling()
方法估算位置偏移量,snapPosition加上位置偏移量就得到最终滚动结束时的位置,也就是targetSnapPosition。
这里有一个点需要注意一下,就是在找targetSnapPosition之前是需要先找一个参考位置的,该参考位置就是snapPosition了。这是因为当前界面上不同的ItemView位置相差比较大,用snapPosition作参考位置,会使得参考位置加上位置偏移量得到的targetSnapPosition最接近目的坐标位置,从而让后续的坐标对齐调整更加自然。
private int estimateNextPositionDiffForFling(RecyclerView.LayoutManager layoutManager,
OrientationHelper helper, int velocityX, int velocityY) {
//计算滚动的总距离,这个距离受到触发fling时的速度的影响
int[] distances = calculateScrollDistance(velocityX, velocityY);
//计算每个ItemView的长度
float distancePerChild = computeDistancePerChild(layoutManager, helper);
if (distancePerChild <= 0) {
return 0;
}
//这里其实就是根据是横向布局还是纵向布局,来取对应布局方向上的滚动距离
int distance =
Math.abs(distances[0]) > Math.abs(distances[1]) ? distances[0] : distances[1];
//distance的正负值符号表示滚动方向,数值表示滚动距离。横向布局方式,内容从右往左滚动为正;竖向布局方式,内容从下往上滚动为正
// 滚动距离/item的长度=滚动item的个数,这里取计算结果的整数部分
if (distance > 0) {
return (int) Math.floor(distance / distancePerChild);
} else {
return (int) Math.ceil(distance / distancePerChild);
}
}
可以看到就是用滚动总距离除以itemview的长度,从而估算得到需要滚动的item数量,此数值就是位置偏移量。而滚动距离是通过SnapHelper的calculateScrollDistance()
方法得到的,ItemView的长度是通过computeDistancePerChild()
方法计算出来。
private float computeDistancePerChild(RecyclerView.LayoutManager layoutManager,
OrientationHelper helper) {
View minPosView = null;
View maxPosView = null;
int minPos = Integer.MAX_VALUE;
int maxPos = Integer.MIN_VALUE;
int childCount = layoutManager.getChildCount();
if (childCount == 0) {
return INVALID_DISTANCE;
}
//循环遍历layoutManager的itemView,得到最小position和最大position,以及对应的view
for (int i = 0; i < childCount; i++) {
View child = layoutManager.getChildAt(i);
final int pos = layoutManager.getPosition(child);
if (pos == RecyclerView.NO_POSITION) {
continue;
}
if (pos < minPos) {
minPos = pos;
minPosView = child;
}
if (pos > maxPos) {
maxPos = pos;
maxPosView = child;
}
}
if (minPosView == null || maxPosView == null) {
return INVALID_DISTANCE;
}
//最小位置和最大位置肯定就是分布在layoutManager的两端,但是无法直接确定哪个在起点哪个在终点(因为有正反向布局)
//所以取两者中起点坐标小的那个作为起点坐标
//终点坐标的取值一样的道理
int start = Math.min(helper.getDecoratedStart(minPosView),
helper.getDecoratedStart(maxPosView));
int end = Math.max(helper.getDecoratedEnd(minPosView),
helper.getDecoratedEnd(maxPosView));
//终点坐标减去起点坐标得到这些itemview的总长度
int distance = end - start;
if (distance == 0) {
return INVALID_DISTANCE;
}
// 总长度 / itemview个数 = itemview平均长度
return 1f * distance / ((maxPos - minPos) + 1);
}
可以发现computeDistancePerChild()
方法也用总长度除以ItemView个数的方式来得到ItemView平均长度,并且也支持了layoutManager不同的布局方式和布局方向。
public int[] calculateScrollDistance(int velocityX, int velocityY) {
int[] outDist = new int[2];
//mGravityScroller是一个Scroller,通过fling()方法模拟fling操作,通过将起点位置都置为0,此时得到的终点位置就是滚动的距离
mGravityScroller.fling(0, 0, velocityX, velocityY,
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
outDist[0] = mGravityScroller.getFinalX();
outDist[1] = mGravityScroller.getFinalY();
return outDist;
}
calculateScrollDistance()
是SnapHelper中的方法,它使用到的mGravityScroller是一个在attachToRecyclerView()
中初始化的Scroller对象,通过Scroller.fling()
方法模拟fling操作,将fling的起点位置为设置为0,此时得到的终点位置就是fling的距离。这个距离会有正负符号之分,表示滚动的方向。
现在明白了吧,LinearSnapHelper的主要功能就是通过实现SnapHelper的三个抽象方法,从而实现辅助RecyclerView滚动Item对齐中心位置。
3.自定义SnapHelper
实现如下效果:
可以看到该效果是一个类似Gallery的横向列表滑动控件,很明显可以用RecyclerView来实现,而滚动后的ItemView是对齐RecyclerView的左边缘位置,这种对齐效果当仍不让就使用了SnapHelper来实现了。这里就主要讲下这个SnapHelper怎么实现的。
创建一个GallerySnapHelper继承SnapHelper实现它的三个抽象方法:
calculateDistanceToFinalSnap()
:计算SnapView当前位置与目标位置的距离
@Override
public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) {
int[] out = new int[2];
if (layoutManager.canScrollHorizontally()) {
out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
} else {
out[0] = 0;
}
return out;
}
//targetView的start坐标与RecyclerView的paddingStart之间的差值
//就是需要滚动调整的距离
private int distanceToStart(View targetView, OrientationHelper helper) {
return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding();
}
findSnapView()
:找到当前时刻的SnapView:
@Override
public View findSnapView(RecyclerView.LayoutManager layoutManager) {
return findStartView(layoutManager, getHorizontalHelper(layoutManager));
}
private View findStartView(RecyclerView.LayoutManager layoutManager, OrientationHelper helper) {
if (layoutManager instanceof LinearLayoutManager) {
//找出第一个可见的ItemView的位置
int firstChildPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
if (firstChildPosition == RecyclerView.NO_POSITION) {
return null;
}
//找到最后一个完全显示的ItemView,如果该ItemView是列表中的最后一个
//就说明列表已经滑动最后了,这时候就不应该根据第一个ItemView来对齐了
//要不然由于需要跟第一个ItemView对齐最后一个ItemView可能就一直无法完全显示,
//所以这时候直接返回null表示不需要对齐
if (((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1) {
return null;
}
View firstChildView = layoutManager.findViewByPosition(firstChildPosition);
//如果第一个ItemView被遮住的长度没有超过一半,就取该ItemView作为snapView
//超过一半,就把下一个ItemView作为snapView
if (helper.getDecoratedEnd(firstChildView) >= helper.getDecoratedMeasurement(firstChildView) / 2 && helper.getDecoratedEnd(firstChildView) > 0) {
return firstChildView;
} else {
return layoutManager.findViewByPosition(firstChildPosition + 1);
}
} else {
return null;
}
}
findTargetSnapPosition()
: 在触发fling时找到targetSnapPosition:
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX,
int velocityY) {
if (!(layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider)) {
return RecyclerView.NO_POSITION;
}
final int itemCount = layoutManager.getItemCount();
if (itemCount == 0) {
return RecyclerView.NO_POSITION;
}
final View currentView = findSnapView(layoutManager);
if (currentView == null) {
return RecyclerView.NO_POSITION;
}
final int currentPosition = layoutManager.getPosition(currentView);
if (currentPosition == RecyclerView.NO_POSITION) {
return RecyclerView.NO_POSITION;
}
RecyclerView.SmoothScroller.ScrollVectorProvider vectorProvider =
(RecyclerView.SmoothScroller.ScrollVectorProvider) layoutManager;
PointF vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1);
if (vectorForEnd == null) {
return RecyclerView.NO_POSITION;
}
int deltaJump;
if (layoutManager.canScrollHorizontally()) {
deltaJump = estimateNextPositionDiffForFling(layoutManager,
getHorizontalHelper(layoutManager), velocityX, 0);
if (vectorForEnd.x < 0) {
deltaJump = -deltaJump;
}
} else {
deltaJump = 0;
}
if (deltaJump == 0) {
return RecyclerView.NO_POSITION;
}
int targetPos = currentPosition + deltaJump;
if (targetPos < 0) {
targetPos = 0;
}
if (targetPos >= itemCount) {
targetPos = itemCount - 1;
}
return targetPos;
}
这个方法跟LinearSnapHelper的实现基本是一样的。