我实现了以下代码。它工作,但我检索它一次,它在我的数据中做了很多重复。如何让它只运行一次检索更多数据?
final LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean loading = true;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int pastVisibleItems, visibleItemCount, totalItemCount;
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisibleItems = layoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
loading = false;
//retrieve more data from internet
loading = true;
}
}
}
});
答案 0 :(得分:1)
事实证明以下算法更好
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mRecyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.i("...", "end called");
// Do something
loading = true;
}
}
});