Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@GuilhE 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