Skip to content

Instantly share code, notes, and snippets.

@aashreys
Last active February 9, 2017 13:23
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 aashreys/451fe2d864daf84c2a8693522be5a9bb to your computer and use it in GitHub Desktop.
Save aashreys/451fe2d864daf84c2a8693522be5a9bb to your computer and use it in GitHub Desktop.
A RecyclerView.Adapter extension which adds a callback to assist in the creation of endlessly scrollable lists i.e. lists which load more data as the user reaches the end.
public class EndlessScrollAdapter extends RecyclerView.Adapter<EndlessScrollAdapter.ImageViewHolder> {
private static final String TAG = EndlessScrollAdapter.class.getSimpleName();
private int loadingThreshold = 5; // Default value
private LoadMoreCallback loadMoreCallback;
public EndlessScrollAdapter() {}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return viewholder
}
@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
// bind viewholder
int currentPosition = holder.getAdapterPosition();
int thresholdDiff = getItemCount() - currentPosition;
if (loadingThreshold >= thresholdDiff && loadMoreCallback != null) {
loadMoreCallback.onLoadMore();
}
}
public void setLoadingThreshold(int lastNItems) {
this.loadingThreshold = lastNItems;
}
public void setLoadMoreCallback(LoadMoreCallback loadMoreCallback) {
this.loadMoreCallback = loadMoreCallback;
}
// Implement this to know when to load more data and add it to the adapter
public interface LoadMoreCallback {
void onLoadMore();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment