Skip to content

Instantly share code, notes, and snippets.

@amilcar-andrade
Created April 15, 2020 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amilcar-andrade/1027f90f4327dc4f8aed98bab23595b3 to your computer and use it in GitHub Desktop.
Save amilcar-andrade/1027f90f4327dc4f8aed98bab23595b3 to your computer and use it in GitHub Desktop.
InfiniteScrollListener
package io.plaidapp.ui.recyclerview;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import io.plaidapp.data.DataLoadingSubject;
/**
* A scroll listener for RecyclerView to load more items as you approach the end.
*
* Adapted from https://gist.github.com/ssinss/e06f12ef66c51252563e
*/
public abstract class InfiniteScrollListener extends RecyclerView.OnScrollListener {
// The minimum number of items remaining before we should loading more.
private static final int VISIBLE_THRESHOLD = 5;
private final LinearLayoutManager layoutManager;
private final DataLoadingSubject dataLoading;
private final Runnable loadMoreRunnable = new Runnable() {
@Override
public void run() {
onLoadMore();
}
};
public InfiniteScrollListener(@NonNull LinearLayoutManager layoutManager,
@NonNull DataLoadingSubject dataLoading) {
this.layoutManager = layoutManager;
this.dataLoading = dataLoading;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// bail out if scrolling upward or already loading data
if (dy < 0 || dataLoading.isDataLoading()) return;
final int visibleItemCount = recyclerView.getChildCount();
final int totalItemCount = layoutManager.getItemCount();
final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) {
recyclerView.post(loadMoreRunnable);
}
}
public abstract void onLoadMore();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment