-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecyclerViewPageChangeListenerHelper.java
58 lines (49 loc) · 2.22 KB
/
RecyclerViewPageChangeListenerHelper.java
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
package com.zorro.core.listener.recylerview;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.view.View;
/**
* Created by pangli on 2018/12/13 9:43
* 备注:RecyclerView实现类似ViewPager的PageChangeListener监听
*/
public class RecyclerViewPageChangeListenerHelper extends RecyclerView.OnScrollListener {
private SnapHelper snapHelper;
private OnPageChangeListener onPageChangeListener;
private int oldPosition = -1;//防止同一Position多次触发
public RecyclerViewPageChangeListenerHelper(SnapHelper snapHelper, OnPageChangeListener onPageChangeListener) {
this.snapHelper = snapHelper;
this.onPageChangeListener = onPageChangeListener;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (onPageChangeListener != null) {
onPageChangeListener.onScrolled(recyclerView, dx, dy);
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
int position = 0;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//获取当前选中的itemView
View view = snapHelper.findSnapView(layoutManager);
if (view != null) {
//获取itemView的position
position = layoutManager.getPosition(view);
}
if (onPageChangeListener != null) {
onPageChangeListener.onScrollStateChanged(recyclerView, newState);
//newState == RecyclerView.SCROLL_STATE_IDLE 当滚动停止时触发防止在滚动过程中不停触发
if (newState == RecyclerView.SCROLL_STATE_IDLE && oldPosition != position) {
oldPosition = position;
onPageChangeListener.onPageSelected(position);
}
}
}
public interface OnPageChangeListener {
void onScrollStateChanged(RecyclerView recyclerView, int newState);
void onScrolled(RecyclerView recyclerView, int dx, int dy);
void onPageSelected(int position);
}
}