Skip to content

Instantly share code, notes, and snippets.

@cdmunoz
Created March 21, 2018 01:06
Show Gist options
  • Save cdmunoz/a3a63db2705debb84a64f9c32cfa1993 to your computer and use it in GitHub Desktop.
Save cdmunoz/a3a63db2705debb84a64f9c32cfa1993 to your computer and use it in GitHub Desktop.
class InfiniteScrollListener(
val func: () -> Unit,
val layoutManager: LinearLayoutManager) : RecyclerView.OnScrollListener() {
private var previousTotal = 0
private var loading = true
private var visibleThreshold = 2
private var firstVisibleItem = 0
private var visibleItemCount = 0
private var totalItemCount = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > 0) {
visibleItemCount = recyclerView.childCount
totalItemCount = layoutManager.itemCount
firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (totalItemCount > previousTotal) {
loading = false
previousTotal = totalItemCount
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// End has been reached
func()
loading = true
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment