RecyclerView 实现分页滚动

转载请附原文链接:

1 需求分析

最近公司项目要实现一个需求要满足以下功能:

1)显示一个 list 列表, item 数量不固定。

2)实现翻页功能,一次翻一页。

3)实现翻至某一页功能。

4)实现一次翻几页功能。

下面介绍通过 RecyclerView 实现该需求的实现过程(效果图如下)。

showimage

2 功能实现

2.1 OnTouchListener 记录当前开始滑动位置

要实现翻页滑动首先我们要确定是向前翻页还是向后翻页,这里通过记录开始翻页前当前的位置和滑动后的位置比较即可得知,下面选择手指触摸按下时滑动的位置为当前开始滑动位置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//当前滑动距离
private int offsetY = 0;
private int offsetX = 0;
//按下屏幕点
private int startY = 0;
private int startX = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
//手指按下的时候记录开始滚动的坐标
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//手指按下的开始坐标
startY = offsetY;
startX = offsetX;
}
return false;
}
}

好了,当我们确定了滑动方向,下面要考虑的就是如何实现滑动?

2.2 scrollTo(int x, int y) 和 scrollBy(int x, int y) 实现滑动

滑动我们最容易想到的方法就是 scrollTo(int x, int y)scrollBy(int x, int y) 这两个方法, scrollTo(int x, int y) 是将当前 View 的内容滑动至某一位置, scrollBy(int x, int y) 是将当前 View 内容相对于当前位置滑动一定的距离,其实 scrollBy(int x, int y) 内部是调用了 scrollTo(int x, int y) 方法实现的 一开始想用 scrollTo(int x, int y) 去实现,但是简单看了下源码发现, RecyclerView 不支持这个方法:

1
2
3
4
5
@Override
public void scrollTo(int x, int y) {
Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. "
+ "Use scrollToPosition instead");
}

所以这里我们就选择使用 scrollBy(int x, int y) 去实现滑动。

2.3 OnFlingListenerOnScrollListener 调用滑动时机

上面我们决定使用 scrollBy(int x, int y) 去实现滑动,那么现在我们就要确定 scrollBy(int x, int y) 这个方法的调用时机,我们知道当我们滑动 RecyclerView 的时候一般分为两种情况,一种是手指在屏幕上面缓慢滑动(Scroll),另一种是飞速滑动(onFling),经过一番查阅,发现 RecyclerView 中有这两种状态的监听,那么我们一起看一下这两种状态的方法定义,先看 onFling(int velocityX, int velocityY)

Note: 由于使用了 RecyclerView 的 OnFlingListener,所以 RecycleView 的版本必须要 recyclerview-v7:25.0.0 以上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* This class defines the behavior of fling if the developer wishes to handle it.
* <p>
* Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior.
*
* @see #setOnFlingListener(OnFlingListener)
*/
public static abstract class OnFlingListener {
/**
* Override this to handle a fling given the velocities in both x and y directions.
* Note that this method will only be called if the associated {@link LayoutManager}
* supports scrolling and the fling is not handled by nested scrolls first.
*
* @param velocityX the fling velocity on the X axis
* @param velocityY the fling velocity on the Y axis
*
* @return true if the fling washandled, false otherwise.
*/
public abstract boolean onFling(int velocityX, int velocityY);
}

方法的注释写的也很清楚,当这个方法被调用并且返回 true 的时候系统就不处理滑动了,而是将滑动交给我们自己处理。所以我们可以监听这个方法,当我们执行快速滑动的时候在这个方法里面计算要滑动的距离并执行 scrollBy(int x, int y) 实现滑动,然后直接返回 true,表示滑动我们自己处理了,不需要系统处理。处理代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//当前滑动距离
private int offsetY = 0;
private int offsetX = 0;
//按下屏幕点
private int startY = 0;
private int startX = 0;
//最后一个可见 view 位置
private int lastItemPosition = -1;
//第一个可见view的位置
private int firstItemPosition = -2;
//总 itemView 数量
private int totalNum;
@Override
public boolean onFling(int velocityX, int velocityY) {
if (mOrientation == ORIENTATION.NULL) {
return false;
}
//获取开始滚动时所在页面的index
int page = getStartPageIndex();
//记录滚动开始和结束的位置
int endPoint = 0;
int startPoint = 0;
//如果是垂直方向
if (mOrientation == ORIENTATION.VERTICAL) {
//开始滚动位置,当前开始执行 scrollBy 位置
startPoint = offsetY;
if(velocityY==Integer.MAX_VALUE){
page +=indexPage;
}else if (velocityY < 0) {
page--;
} else if (velocityY > 0) {
page++;
} else if (pageNum != -1) {
startPoint=0;
page = pageNum-1;
}
//更具不同的速度判断需要滚动的方向
//一次滚动一个 mRecyclerView 高度
endPoint = page * mRecyclerView.getHeight();
} else {
startPoint = offsetX;
if(velocityX==Integer.MAX_VALUE){
page +=indexPage;
}else if (velocityX < 0) {
page--;
} else if (velocityX > 0) {
page++;
} else if (pageNum != -1) {
startPoint=0;
page = pageNum-1;
}
endPoint = page * mRecyclerView.getWidth();
}
//使用动画处理滚动
if (mAnimator == null) {
mAnimator = ValueAnimator.ofInt(startPoint, endPoint);
mAnimator.setDuration(300);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int nowPoint = (int) animation.getAnimatedValue();
if (mOrientation == ORIENTATION.VERTICAL) {
int dy = nowPoint - offsetY;
if (dy == 0) return;
//这里通过RecyclerView的scrollBy方法实现滚动。
mRecyclerView.scrollBy(0, dy);
} else {
int dx = nowPoint - offsetX;
mRecyclerView.scrollBy(dx, 0);
}
}
});
mAnimator.addListener(new AnimatorListenerAdapter() {
//动画结束
@Override
public void onAnimationEnd(Animator animation) {
//回调监听
if (null != mOnPageChangeListener) {
mOnPageChangeListener.onPageChange(getPageIndex());
}
startY = offsetY;
startX = offsetX;
//滚动完成,进行判断是否滚到头了或者滚到尾部了
RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
//判断是当前layoutManager是否为LinearLayoutManager
// 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
//获取最后一个可见view的位置
lastItemPosition = linearManager.findLastVisibleItemPosition();
//获取第一个可见view的位置
firstItemPosition = linearManager.findFirstVisibleItemPosition();
}
totalNum = mRecyclerView.getAdapter().getItemCount();
if (totalNum == lastItemPosition + 1) {
updateLayoutManger();
}
if (firstItemPosition == 0) {
updateLayoutManger();
}
}
});
} else {
mAnimator.cancel();
mAnimator.setIntValues(startPoint, endPoint);
}
mAnimator.start();
return true;
}
}
}

再看 OnScrollListener 滚动监听方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public abstract static class OnScrollListener {
/**
* Callback method to be invoked when RecyclerView's scroll state changes.
*
* @param recyclerView The RecyclerView whose scroll state has changed.
* @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
*/
public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
* 滚动完成调用
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
}

这个监听类主要有两个方法一个是 onScrollStateChanged(RecyclerView recyclerView, int newState) 滚动状态发生变化调用, onScrolled(RecyclerView recyclerView, int dx, int dy) RecyclerView 发生滚动和滚动完成调用。有了这两个监听,当我们进行缓慢滑动我们就可以在 onScrollStateChanged(RecyclerView recyclerView, int newState) 中监听滑动如果结束并且超过一定距离去执行翻页,而通过 onScrolled(RecyclerView recyclerView, int dx, int dy) 方法可以记录当前的滑动距离。处理方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//如果滑动停止
if (newState == RecyclerView.SCROLL_STATE_IDLE && mOrientation != ORIENTATION.NULL) {
boolean move;
int vX = 0, vY = 0;
if (mOrientation == ORIENTATION.VERTICAL) {
int absY = Math.abs(offsetY - startY);
//如果滑动的距离超过屏幕的一半表示需要滑动到下一页
move = absY > recyclerView.getHeight() / 2;
vY = 0;
if (move) {
vY = offsetY - startY < 0 ? -1000 : 1000;
}
} else {
int absX = Math.abs(offsetX - startX);
move = absX > recyclerView.getWidth() / 2;
if (move) {
vX = offsetX - startX < 0 ? -1000 : 1000;
}
}
//调用滑动
mOnFlingListener.onFling(vX, vY);
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//滚动结束记录滚动的偏移量
//记录当前滚动到的位置
offsetY += dy;
offsetX += dx;
}
}

到这里我们要实现滑动的方法和时机基本就搞定了,剩下的就是滑动位置计算和滑动效果实现,滑动位置计算就是一次滑动一整页,这个没什么可说的,所以简单说下实现弹性滑动效果。

2.4 ValueAnimator 实现弹性滑动效果

我们知道如果我们直接调用 scrollBy(int x, int y) 这个方法去滑动,那么是没有缓慢滑动的效果,看着有点愣,所以这里我们通过 ValueAnimator 这个类来实现缓慢滑动的效果,这个就很简单了,直接贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (mAnimator == null) {
mAnimator = ValueAnimator.ofInt(startPoint, endPoint);
mAnimator.setDuration(300);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int nowPoint = (int) animation.getAnimatedValue();
if (mOrientation == ORIENTATION.VERTICAL) {
int dy = nowPoint - offsetY;
if (dy == 0) return;
//这里通过RecyclerView的scrollBy方法实现滚动。
mRecyclerView.scrollBy(0, dy);
} else {
int dx = nowPoint - offsetX;
mRecyclerView.scrollBy(dx, 0);
}
}
});

2.5 翻页至某一页

这里翻页至某一页的实现有了上面的基础就很好实现了,就是直接调用 我们已经实现好了的 onFling(int velocityX, int velocityY) 方法,然后把页数传递过去计算一下就可以了 :

1
2
3
4
public void setPageNum(int page) {
this.pageNum = page;
mOnFlingListener.onFling(0, 0);
}

2.6 一次翻 n 页

1
2
3
4
public void setIndexPage(int indexPage){
this.indexPage=indexPage;
mOnFlingListener.onFling(Integer.MAX_VALUE,Integer.MAX_VALUE);
}

2.7 滑动至某点

1
2
3
4
5
6
7
8
9
10
11
private void scrollTo() {
if(!isPageModel)return;
recyclerView.post(new Runnable() {
@Override
public void run() {
String num= TextUtils.isEmpty(etPageNum.getText().toString().trim()) ? "0" : etPageNum.getText().toString().trim();
vLinearLayoutManager.scrollToPositionWithOffset(0, -Integer.valueOf(num));
}
});
}

滑动至某一点这里是通过 LinearLayoutManager.scrollToPositionWithOffset(int position, int offset)这个方法实现的,因为 RecyclerView. scrollTo(int x, int y) 这个方法无法实现滑动,如果你有更好的方法也求分享下 ^^。

2.8 滑动一定距离

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private void scrollBy() {
if(!isPageModel)return;
String num= TextUtils.isEmpty(etPageNum.getText().toString().trim()) ? "0" : etPageNum.getText().toString().trim();
scrollBy=Integer.valueOf(num);
recyclerView.post(new Runnable() {
@Override
public void run() {
if (mAnimator == null) {
mAnimator = ValueAnimator.ofInt(0, 1);
mAnimator.setDuration(300);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//获取动画完成比例值
float fraction = mAnimator.getAnimatedFraction();
int scroll = (int) (scrollBy * (fraction - lastFraction));
//根据比例值对目标view进行滑动
recyclerView.scrollBy(0,scroll);
lastFraction=fraction;
}
});
mAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if(scrollHelper!=null){
scrollHelper.updateLayoutManger();
}
lastFraction=0;
}
});
} else {
mAnimator.cancel();
mAnimator.setIntValues(0, 1);
}
mAnimator.start();
}
});
}

到这里前面说的功能已经全部实现完毕,具体代码细节请见 github 地址: pagerecyclerview

参考文章:

一行代码让RecyclerView变身ViewPager