Skip to content

Instantly share code, notes, and snippets.

@antonshkurenko
Created October 11, 2015 15:00
Show Gist options
  • Save antonshkurenko/711897e251002823e840 to your computer and use it in GitHub Desktop.
Save antonshkurenko/711897e251002823e840 to your computer and use it in GitHub Desktop.
Endless scroll listener
/**
* This will ensure that this SwipeableRecyclerViewTouchListener is paused during list view scrolling.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener.
*/
public static abstract class EndlessScrollListener extends RecyclerView.OnScrollListener {
private int mPreviousTotal = 0; // The total number of items in the dataset after the last load
private boolean mLoading = true; // True if we are still waiting for the last set of data to load.
private int mVisibleThreshold = 3; // The minimum amount of items to have below your current scroll position before mLoading more.
private int mFirstVisibleItem, mVisibleItemCount, mTotalItemCount;
private int mCurrentPage = 1;
private LinearLayoutManager mLinearLayoutManager;
public EndlessScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mVisibleItemCount = recyclerView.getChildCount();
mTotalItemCount = mLinearLayoutManager.getItemCount();
mFirstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (mLoading) {
if (mTotalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = mTotalItemCount;
}
}
if (!mLoading && (mTotalItemCount - mVisibleItemCount)
<= (mFirstVisibleItem + mVisibleThreshold)) {
// End has been reached
// Do something
mCurrentPage++;
onLoadMore(mCurrentPage);
mLoading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment