滑动监听.gif先看效果图:
//设置RecyclerView滑动监听器 addOnScrollListener(),其中setOnScrollListener()方法已过时
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//获得recyclerView的线性布局管理器
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//获取到第一个item的显示的下标 不等于0表示第一个item处于不可见状态 说明列表没有滑动到顶部 显示回到顶部按钮
int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 判断是否滚动超过一屏
if (firstVisibleItemPosition == 0) {
ivTop.setVisibility(View.GONE);
} else {
//显示回到顶部按钮
ivTop.setVisibility(View.VISIBLE);
}
//获取RecyclerView滑动时候的状态
} else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
ivTop.setVisibility(View.GONE);
}
}
});
RecyclerView有三个滑动状态:
- 当前的recycleView不滑动(滑动已经停止时)
public static final int SCROLL_STATE_IDLE = 0;
- 当前的recycleView被拖动滑动
public static final int SCROLL_STATE_DRAGGING = 1;
- 当前的recycleView在滚动到某个位置的动画过程,但没有被触摸滚动.调用 scrollToPosition(int) 应该会触发这个状态
public static final int SCROLL_STATE_SETTLING = 2;
网友评论