滑动监听,判断是否滑动到了最后一个条目
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
//用来标记是否正在向最后一个滑动
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//设置什么布局管理器,就获取什么的布局管理器
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当停止滑动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//获取最后一个完全显示的ItemPosition ,角标值
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
//所有条目,数量值
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部,并且是向右滚动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
//加载更多功能的代码
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//dx用来判断横向滑动方向,dy用来判断纵向滑动方向
//dx>0:向右滑动,dx<0:向左滑动
//dy>0:向下滑动,dy<0:向上滑动
if (dy > 0) {
isSlidingToLast = true;
} else {
isSlidingToLast = false;
}
}
});
或者用下列方法
public abstract class OnLoadMoreListener extends RecyclerView.OnScrollListener {
private LinearLayoutManager layoutManager;
private int itemCount, lastPosition, lastItemCount;
public abstract void onLoadMore();
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
itemCount = layoutManager.getItemCount();
lastPosition = layoutManager.findLastCompletelyVisibleItemPosition();
} else {
Log.e("OnLoadMoreListener", "The OnLoadMoreListener only support LinearLayoutManager");
return;
}
if (lastItemCount != itemCount && lastPosition == itemCount - 1) {
lastItemCount = itemCount;
this.onLoadMore();
}
}
}