Skip to content

Instantly share code, notes, and snippets.

@antonKozyriatskyi
Last active January 29, 2020 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonKozyriatskyi/1a822697cda45cca8ab62863ea480ada to your computer and use it in GitHub Desktop.
Save antonKozyriatskyi/1a822697cda45cca8ab62863ea480ada to your computer and use it in GitHub Desktop.
Load more listener for RecyclerView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class LoadMoreListener(
private val threshold: Int,
private val listener: OnLoadMoreRequestedListener
) : RecyclerView.OnScrollListener() {
companion object {
fun attach(
threshold: Int,
recyclerView: RecyclerView,
listener: OnLoadMoreRequestedListener
) {
recyclerView.addOnScrollListener(LoadMoreListener(threshold, listener))
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val isScrollingToBottom = dy > 0
if (isScrollingToBottom) {
val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
val lastIndex = layoutManager.itemCount - 1
val lastVisiblePosition = layoutManager.findLastVisibleItemPosition()
val itemsToBottom = lastIndex - lastVisiblePosition
val thresholdMet = itemsToBottom <= threshold
if (thresholdMet) {
listener.onLoadMoreRequested()
}
}
}
interface OnLoadMoreRequestedListener {
fun onLoadMoreRequested()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment