Skip to content

Instantly share code, notes, and snippets.

@Popalay
Created March 22, 2017 14:48
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 Popalay/14bcc2f77bf4835a5a16ef90b0941b77 to your computer and use it in GitHub Desktop.
Save Popalay/14bcc2f77bf4835a5a16ef90b0941b77 to your computer and use it in GitHub Desktop.
public class PaginationScrollListener extends RecyclerView.OnScrollListener {
private static final int ITEMS_OFFSET_TO_LOAD_DEFAULT = 3;
private final OnRecyclerViewScrolledToPageListener mCallback;
private final int mOffset;
private LinearLayoutManager mLayoutManager;
private boolean loading;
private int previousTotal;
public interface OnRecyclerViewScrolledToPageListener {
void onRecyclerViewScrolledToEnd();
}
public PaginationScrollListener(OnRecyclerViewScrolledToPageListener callback) {
this.mCallback = callback;
this.mOffset = ITEMS_OFFSET_TO_LOAD_DEFAULT;
if (mCallback == null) {
throw new IllegalStateException("OnRecyclerViewScrolledToPageListener is NULL");
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (mLayoutManager == null) {
mLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
}
final int visibleItemCount = recyclerView.getChildCount();
final int totalItemCount = mLayoutManager.getItemCount();
final int firstVisibleItem = mLayoutManager.findFirstCompletelyVisibleItemPosition();
final int lastVisibleItem = firstVisibleItem + visibleItemCount;
if (loading) {
if (totalItemCount != previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (lastVisibleItem + mOffset) > totalItemCount) {
// End has been reached
mCallback.onRecyclerViewScrolledToEnd();
// Do something
loading = true;
}
}
public void reset() {
loading = false;
previousTotal = -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment