recyclerView列表分页加载数据
时间: 2023-07-27 11:12:28 浏览: 43
RecyclerView 列表分页加载数据的基本思路是,在滚动到列表底部时触发加载下一页数据的操作。一般来说,我们需要维护以下几个变量:
- currentPage:当前已加载的页数;
- totalPage:总页数;
- isLoading:是否正在加载数据;
- isLastPage:是否已经加载完所有数据。
具体实现步骤如下:
1. 在 RecyclerView 的滚动事件中判断是否滚动到了列表底部。
```java
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int visibleItemCount = linearLayoutManager.getChildCount();
int totalItemCount = linearLayoutManager.getItemCount();
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
if (!isLoading && !isLastPage) {
if (visibleItemCount + firstVisibleItemPosition >= totalItemCount
&& firstVisibleItemPosition >= 0) {
loadNextPage();
}
}
}
});
```
2. 在 loadNextPage() 方法中执行加载下一页数据的操作。
```java
private void loadNextPage() {
isLoading = true;
currentPage++;
// 调用 API 加载下一页数据
apiService.getNextPageData(currentPage).enqueue(new Callback<DataResponse>() {
@Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
if (response.isSuccessful()) {
List<Data> data = response.body().getData();
// 将新数据添加到列表中
dataList.addAll(data);
adapter.notifyDataSetChanged();
isLoading = false;
if (currentPage == totalPage) {
isLastPage = true;
}
} else {
// 加载失败
Toast.makeText(getContext(), "Failed to load data.", Toast.LENGTH_SHORT).show();
isLoading = false;
}
}
@Override
public void onFailure(Call<DataResponse> call, Throwable t) {
// 加载失败
Toast.makeText(getContext(), "Failed to load data.", Toast.LENGTH_SHORT).show();
isLoading = false;
}
});
}
```
3. 在调用 API 加载下一页数据的时候,需要将 currentPage 加 1,并且在加载成功后判断是否已经加载完所有数据。
```java
if (currentPage == totalPage) {
isLastPage = true;
}
```
这里需要注意的是,totalPage 的值需要在第一次加载数据时从 API 中获取,或者在第一次加载成功后计算得出。