Skip to content

Instantly share code, notes, and snippets.

@cdmunoz
Created March 21, 2018 03:37
Show Gist options
  • Save cdmunoz/3871f7a53b04e232e30191d0ac4b47e4 to your computer and use it in GitHub Desktop.
Save cdmunoz/3871f7a53b04e232e30191d0ac4b47e4 to your computer and use it in GitHub Desktop.
package co.cdmunoz.cryptocurrencyapp.utils
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
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