Skip to content

Instantly share code, notes, and snippets.

@GuilhE
Last active December 12, 2018 17:08
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 GuilhE/cb2284d65d9ac9f1fd07bd5723b55924 to your computer and use it in GitHub Desktop.
Save GuilhE/cb2284d65d9ac9f1fd07bd5723b55924 to your computer and use it in GitHub Desktop.
Helper listener class to implement pagination
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* @author gdelgado
* @see <a href="https://gist.github.com/GuilhE/cb2284d65d9ac9f1fd07bd5723b55924">EndlessRecyclerOnScrollListener</a>
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
private LinearLayoutManager layoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItemIndex = layoutManager.findFirstVisibleItemPosition();
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int delta = layoutManager.getOrientation() == LinearLayoutManager.HORIZONTAL ? dx : dy;
boolean startToEnd = !layoutManager.getReverseLayout();
if ((startToEnd ? delta > 0 : delta < 0) && (firstVisibleItemIndex + visibleItemCount >= totalItemCount)) {
onLoadMore(layoutManager.findLastVisibleItemPosition());
}
}
public abstract void onLoadMore(int lastVisibleIndex);
}
@GuilhE
Copy link
Author

GuilhE commented Jul 12, 2018

Just create a new instance of this listener and add it to your RecyclerView:

recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener((LinearLayoutManager) recyclerView.getLayoutManager()) {
        @Override
         public void onLoadMore(int lastVisibleIndex) {
                  //load logic
         }
});

Works with both:
Orientations: LinearLayoutManager.VERTICAL, LinearLayoutManager.HORIZONTAL
Directions: reverseLayout = false (start to end), reverseLayout = true (end to start)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment