使RecyclerView分页在两个方向上工作。
在上下移动时使用分页。 即在到达结尾时以及到达顶部时获取记录。不知何故,我最终得到了错误的页码(第一个可见项目的轨迹和最后一个可见项目索引位置)
说我要显示1万条记录 [The Pool] 。我无法将所有这些数据保存在内存中,并且无法在RecyclerView
中一次显示所有记录。因此,我的方法是随时在RecyclerView.Adapter
中保留几百条记录 [窗口] ,并查询到达{<1}}和next
数据强>端点即可。
previous
我最终得到了错误的[The BUG]
和last page
,从而导致了适配器有重复的数据。 first page
只是一个用于配置预设的类。
当recyclerView到达底端时调用Manager
。
onLoadNext
被召唤。onLoadPrev
private EndlessRecyclerViewScrollListener getScrollListener(final EndlessRecyclerViewScrollListener.Manager manager) {
return new EndlessRecyclerViewScrollListener(manager, recyclerViewPhotos.getLayoutManager()) {
@SuppressWarnings("UnnecessaryLocalVariable")
@Override
public void onLoadNext(final int page, int totalItemsCount, final RecyclerView view) {
System.out.println(">>>>> LOAD NEXT PAGE " + page + " total " + totalItemsCount);
AsyncTask<Object, Integer, MinimalPhotoWithUser[]> task = new AsyncTask<Object, Integer, MinimalPhotoWithUser[]>() {
int offset;
int limit;
@Override
protected void onPreExecute() {
offset = page * PER_PAGE;
limit = PER_PAGE;
}
@Override
protected MinimalPhotoWithUser[] doInBackground(Object... args) {
final long lastPhoto_ID = photosAdapter.getLastDisplayedPhotoId(dbHelper);
Cursor cursor = dbHelper.fetchPhotoRecordsAfterID(lastPhoto_ID, PER_PAGE);
if (cursor != null && cursor.getCount() > 0) {
return MinimalPhotoWithUser.photoWithUsers(cursor);
}
return null;
}
@Override
protected void onPostExecute(final MinimalPhotoWithUser[] photos) {
if (photos != null && photos.length > 0) {
recyclerViewPhotos.post(new Runnable() {
@Override
public void run() {
photosAdapter.appendSamples(photos);
loadNextComplete();
}
});
} else {
fetchPhotosFromWeb();
}
}
};
// execute
task.execute();
}
@Override
public void onLoadPrev(final int page, int totalItemsCount, final RecyclerView view) {
System.out.println(">>>>> LOAD PREV PAGE " + page + " total " + totalItemsCount);
if (page < 0) {
Toast.makeText(getContext(), "no more prev pages", Toast.LENGTH_SHORT).show();
return;
}
AsyncTask<Object, Integer, MinimalPhotoWithUser[]> task = new AsyncTask<Object, Integer, MinimalPhotoWithUser[]>() {
int offset;
int limit;
@Override
protected void onPreExecute() {
offset = page * PER_PAGE;
limit = PER_PAGE;
}
@Override
protected MinimalPhotoWithUser[] doInBackground(Object... args) {
final long lastPhoto_ID = photosAdapter.getFirstDisplayedPhotoId(dbHelper);
Cursor cursor = dbHelper.fetchPhotoRecordsBeforeID(lastPhoto_ID, PER_PAGE);
if (cursor != null && cursor.getCount() > 0) {
return MinimalPhotoWithUser.photoWithUsers(cursor);
}
return null;
}
@Override
protected void onPostExecute(final MinimalPhotoWithUser[] photos) {
if (photos != null) {
recyclerViewPhotos.post(new Runnable() {
@Override
public void run() {
photosAdapter.prependSamples(photos);
loadPrevComplete();
}
});
}
}
};
// execute
task.execute();
}
};
[注意:此代码通常显示照片,与照片相关的代码检查数据库是否存在当前位置后的数据,然后从数据库中取出记录,否则从网络请求中提取记录,然后将其添加到数据库中适配器]