Skip to content

Instantly share code, notes, and snippets.

@skydoves
Created March 16, 2018 02:44
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save skydoves/a0b972131c7fe5baf2ddf3d8325f3c6a to your computer and use it in GitHub Desktop.
RecyclerViewPaginator
class RecyclerViewPaginator(val recyclerView: RecyclerView,
val isLoading: () -> Boolean,
val loadMore: (Int) -> Unit,
val onLast: () -> Boolean = { true }): RecyclerView.OnScrollListener() {
private val threshold = 10
private var currentPage: Int = 0
init {
recyclerView.addOnScrollListener(this)
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager
val visibleItemCount = recyclerView.layoutManager.childCount
val totalItemCount = recyclerView.layoutManager.itemCount
val firstVisibleItemPosition = when (layoutManager) {
is LinearLayoutManager -> layoutManager.findLastVisibleItemPosition()
is GridLayoutManager -> layoutManager.findLastVisibleItemPosition()
else -> return
}
if (onLast() || isLoading()) return
if ((visibleItemCount + firstVisibleItemPosition + threshold) >= totalItemCount) {
loadMore(++currentPage)
}
}
fun resetCurrentPage() {
this.currentPage = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment