在使用RecyclerView时,经常需要检测用户是否滑动到顶部或底部
private void addOnScrollListener() {
//为RecyclerView添加OnScrollListener,监控滑动事件
mPhotoRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
private int lastVisibleItemPosition;
private int firstVisibleItemPosition;
//滑动结束时,将回调onScrolled接口
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
super.onScrolled(recyclerView, dx, dy);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
//得到当前界面,最后一个子视图对应的position
lastVisibleItemPosition = ((GridLayoutManager) layoutManager)
.findLastVisibleItemPosition();
//得到当前界面,第一个子视图的position
firstVisibleItemPosition = ((GridLayoutManager) layoutManager)
.findFirstVisibleItemPosition();
................
}
}
//当滑动状态发生改变时,回调该接口
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//得到当前界面可见数据的大小
int visibleItemCount = layoutManager.getChildCount();
//得到RecyclerView对应所有数据的大小
int totalItemCount = layoutManager.getItemCount();
//判断条件可按实际需要调整
if (newState == RecyclerView.SCROLL_STATE_IDLE && visibleItemCount > 0) {
//最后视图对应的position等于总数-1时,说明上一次滑动结束时,触底了
if (lastVisibleItemPosition == totalItemCount - 1){
//按需进行业务
startURLLoader();
//第一个视图的position等于0,说明上一次滑动结束时,触顶了
} else if (firstVisibleItemPosition == 0) {
Toast.makeText(getActivity(),
"Already to the top",
Toast.LENGTH_SHORT)
.show();
}
}
}
});
}
网友评论