Created
April 15, 2020 21:25
-
-
Save amilcar-andrade/1027f90f4327dc4f8aed98bab23595b3 to your computer and use it in GitHub Desktop.
InfiniteScrollListener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.plaidapp.ui.recyclerview; | |
import android.support.annotation.NonNull; | |
import android.support.v7.widget.LinearLayoutManager; | |
import android.support.v7.widget.RecyclerView; | |
import io.plaidapp.data.DataLoadingSubject; | |
/** | |
* A scroll listener for RecyclerView to load more items as you approach the end. | |
* | |
* Adapted from https://gist.github.com/ssinss/e06f12ef66c51252563e | |
*/ | |
public abstract class InfiniteScrollListener extends RecyclerView.OnScrollListener { | |
// The minimum number of items remaining before we should loading more. | |
private static final int VISIBLE_THRESHOLD = 5; | |
private final LinearLayoutManager layoutManager; | |
private final DataLoadingSubject dataLoading; | |
private final Runnable loadMoreRunnable = new Runnable() { | |
@Override | |
public void run() { | |
onLoadMore(); | |
} | |
}; | |
public InfiniteScrollListener(@NonNull LinearLayoutManager layoutManager, | |
@NonNull DataLoadingSubject dataLoading) { | |
this.layoutManager = layoutManager; | |
this.dataLoading = dataLoading; | |
} | |
@Override | |
public void onScrolled(RecyclerView recyclerView, int dx, int dy) { | |
// bail out if scrolling upward or already loading data | |
if (dy < 0 || dataLoading.isDataLoading()) return; | |
final int visibleItemCount = recyclerView.getChildCount(); | |
final int totalItemCount = layoutManager.getItemCount(); | |
final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); | |
if ((totalItemCount - visibleItemCount) <= (firstVisibleItem + VISIBLE_THRESHOLD)) { | |
recyclerView.post(loadMoreRunnable); | |
} | |
} | |
public abstract void onLoadMore(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment