我正在使用RecyclerView和StaggeredGridLayoutManager以及無盡滾動。當列表的最後一項對用戶可見時,我想進行網絡調用。所以這裏是我的代碼:Recyclerview StaggeredGridLayoutManager - 查找最後一個可見項
public RecyclerViewAdapter(Context context) {
Log.d(Const.DEBUG, "RecyclerViewAdapter Constructor()");
this.context = context;
final StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = staggeredGridLayoutManager.getItemCount();
lastVisibleItems = staggeredGridLayoutManager.findLastVisibleItemPositions(new int[mStaggeredLayoutManager.getSpanCount()]);
Log.d(Const.DEBUG, "LastVisibleItems: " + Arrays.toString(lastVisibleItems));
Log.d(Const.DEBUG, "LastVisibleItems Count: " + lastVisibleItems.length);
if (staggeredGridLayoutManager.getSpanCount() == 1) {
lastVisibleItem = lastVisibleItems[0];
} else if (staggeredGridLayoutManager.getSpanCount() == 2) {
lastVisibleItem = Math.max(lastVisibleItems[0], lastVisibleItems[1]);
} else if (staggeredGridLayoutManager.getSpanCount() == 3) {
lastVisibleItem = Math.max(Math.max(lastVisibleItems[0], lastVisibleItems[1]), lastVisibleItems[2]);
}
if (!isRefreshing && (totalItemCount <= lastVisibleItem + visibleThreshold)) {
Log.d(Const.DEBUG, "isRefreshing: " + isRefreshing);
Log.d(Const.DEBUG, "totalItemCount: " + totalItemCount);
Log.d(Const.DEBUG, "lastVisibileItem: " + lastVisibleItem);
Log.d(Const.DEBUG, "visibileThreshold: " + visibleThreshold);
Log.d(Const.DEBUG, "calling LoadMore()");
if (mIOnLoadMoreListener != null) {
mIOnLoadMoreListener.onLoadMore();
}
isRefreshing = true;
}
}
});
}
我在第一次調用時從服務器獲得9個值。所以,當我移動到最後一個索引[8]時,lastVisibleItem將爲8,visibleThreshold爲1,totalItemCount爲9,因此下一次網絡調用應該發生。現在實際發生的情況是,當屏幕第一次加載時,lastVisibleItem應該是1或2,但是它返回8,結果,loadMore()被調用。
的logcat:
D/xx: Items Count: 9
D/xx: LastVisibleItems: [8]
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: LastVisibleItems Count: 1
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: isRefreshing: false
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: totalItemCount: 9
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: lastVisibileItem: 8
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: visibileThershold: 1
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: calling LoadMore()
03-22 15:22:52.772 5957-5957/codsiga.com.xx D/xx: onLoadMore()
03-22 15:22:52.798 5957-5957/codsiga.com.xx D/xx: getDataFromServer()
什麼是錯在上面的代碼?需要幫助請叫我。相同的代碼之前運作良好。