发布时间:2023-03-21 19:30
第一种方法:
//上滑加载更多
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
int totalItemCount = recyclerView.getAdapter().getItemCount();
int lastVisibleItemPosition = lm.findLastVisibleItemPosition();
int visibleItemCount = recyclerView.getChildCount();
if (newState == RecyclerView.SCROLL_STATE_IDLE
&& lastVisibleItemPosition == totalItemCount - 1
&& visibleItemCount > 0) {
//加载更多
addMoreData();
adapter.notifyItemInserted(adapter.getItemCount());
}
}
});
}
第二种方法:
//上滑加载更多
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager gm = (LinearLayoutManager) recyclerView.getLayoutManager();
//获取最后一个item的位置
int lastItem = gm.findLastVisibleItemPosition();
if (newState == RecyclerView.SCROLL_STATE_IDLE && adapter.getItemCount() >= lastItem){
//获取更多数据
addMoreData();
//刷新一下适配器
adapter.notifyItemInserted(adapter.getItemCount());
}
}
});
}