Skip to content

Instantly share code, notes, and snippets.

@jutikorn
Last active June 26, 2017 03:07
Show Gist options
  • Save jutikorn/3b6afbf211ea08b3a45c49a1910bdaa0 to your computer and use it in GitHub Desktop.
Save jutikorn/3b6afbf211ea08b3a45c49a1910bdaa0 to your computer and use it in GitHub Desktop.
Load more listener for RecyclerView
fun RecyclerView.onLoadMoreListener(onLoadMore: (Int) -> Unit) {
layoutManager?.let {
this.addOnScrollListener(object : RecyclerView.OnScrollListener() {
var previousTotal = 0
var loading = true
var visibleThreshold = 5
var firstVisibleItem = 0
var visibleItemCount = 0
var totalItemCount = 0
var currentPage = 1
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
visibleItemCount = childCount
totalItemCount = layoutManager.itemCount
firstVisibleItem = (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
if (loading && totalItemCount > previousTotal) {
loading = false
previousTotal = totalItemCount
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
currentPage++
onLoadMore(currentPage)
loading = true
}
}
})
}
}
@jutikorn
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment