I have a RecyclerView
that im trying to implement an infinite scroll feature into. The issue is, the code inside the if statements in the OnScrolled
method is being executed twice. Heres my current code:
public abstract class InfiniteScroll extends RecyclerView.OnScrollListener {
private LinearLayoutManager mLayoutManager;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 1;
public InfiniteScroll(LinearLayoutManager layoutManager) {
mLayoutManager = layoutManager;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = recyclerView.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
// Do something
current_page++;
Log.d("moreitems", "why is this being called twice?");
loadMore(current_page);
loading = true;
}
}
public abstract void loadMore(int current_page);
}
This code was posted as an answer to a separate SO question, and other examples seem to function similar, but I still get the loadMore()
method executing twice when reaching the bottom of the RecyclerView
, and im not sure why.
it's getting called because when you loadMore items, onScrolled is called again.
This callback will also be called if visible item range changes after a layout calculation. In that case, dx and dy will be 0.
so you could check
if (!loading && dy>0)
as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With