我正在学习Android并尝试为记录的ListView实现分页(或无限滚动)。
我正在使用ListView的setOnScrollListener读取列表向下滚动并记录结束,这样我就可以对我的服务器进行API调用并获取下一组数据。
当列表一直向下滚动并且一直向上(因此可以获取下一个/上一组数据)时,我仍然试图弄清楚如何读取数据的结尾
accountList.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
Log.i("SCROLL", "-----firstVisibleItem: " + firstVisibleItem + " | visibleItemCount: " + visibleItemCount + " | totalItemCount: " + totalItemCount + " | pageIndex: " + pageIndex);
if((firstVisibleItem + visibleItemCount >= totalItemCount) && totalItemCount > 0) {
Log.i("SCROLL", "-------- we have reached at the bottom of the scroll list");
pageIndex = pageIndex + pageSize;
getAllAccountsRecords();
} else if(firstVisibleItem == 0 && visibleItemCount > 0 && totalItemCount > 0 && pageIndex > 0) {
Log.i("SCROLL", "-------- we have reached at the top of the scroll list");
pageIndex = pageIndex - pageSize;
if(pageIndex >= 0) {
getAllAccountsRecords();
}
}
}
});
getAllAccountsRecords调用AsyncTask并执行API调用以重新填充listview。
public void getAllAccountsRecords() {
new GetAccounts().execute();
}
然而,无论何时我一直向下滚动到初始数据集,它都会进入一个疯狂的循环并开始递增来自0>的pageIndex值。 10> 20> 30> 40 ......等等
以下是调试日志
I: -----firstVisibleItem: 3 | visibleItemCount: 5 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 3 | visibleItemCount: 5 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 3 | visibleItemCount: 5 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 3 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 3 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 3 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 0
I: -----firstVisibleItem: 4 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 0
I: -------- we have reached at the bottom of the scroll list
I: -----firstVisibleItem: 4 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 10
I: -------- we have reached at the bottom of the scroll list
I: -----firstVisibleItem: 4 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 20
I: -------- we have reached at the bottom of the scroll list
I: -----firstVisibleItem: 4 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 30
I: -------- we have reached at the bottom of the scroll list
I: -----firstVisibleItem: 0 | visibleItemCount: 6 | totalItemCount: 10 | pageIndex: 40
I: -----firstVisibleItem: 0 | visibleItemCount: 0 | totalItemCount: 0 | pageIndex: 40
I: -----firstVisibleItem: 0 | visibleItemCount: 0 | totalItemCount: 0 | pageIndex: 40
I: -----firstVisibleItem: 0 | visibleItemCount: 0 | totalItemCount: 0 | pageIndex: 40
因此它永远不会将firstVisibleItem初始化为0,因此pageIndex会不断增加。
我看过许多无限滚动解决方案,但它们都是从静态来源获取数据而对我不起作用,所以我不得不想出自己的
任何帮助解决这个问题或让它变得更好的人都会受到赞赏。
感谢。