Skip to content

Instantly share code, notes, and snippets.

@maxost
Created September 5, 2017 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxost/be029008600680232984c49d9d1b681b to your computer and use it in GitHub Desktop.
Save maxost/be029008600680232984c49d9d1b681b to your computer and use it in GitHub Desktop.
Kotlin: RecyclerView assign on scroll to end listener
fun RecyclerView.onScrollToEnd(linearLayoutManager: LinearLayoutManager, onScrollNearEnd: (Unit) -> Unit)
= addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
if (linearLayoutManager.childCount + linearLayoutManager.findFirstVisibleItemPosition()
>= linearLayoutManager.itemCount - 5) { //if near fifth item from end
onScrollNearEnd(Unit)
}
}
})
@Fatimamostafa
Copy link

Can you show me a example usage of this?

@tomkeane07
Copy link

kotlin beginner: would love to see an example of how this could be used..

@Jhosse
Copy link

Jhosse commented Jun 4, 2020

All that you have to do is, add the listener to the recyclerView (same place where you set the recyclerView itself, ie: onCreateView), something like ...
YOUR_RECYCLER_VIEW.onScrollToEnd(linearLayoutManager) { THE_FUNCTION_YOU_WANT_TO_CALL() }
If you just need to call a function at the end of the scroll, you don't even need to pass the LinearLayoutManager. You can change the listener to:

fun RecyclerView.onScrollToEnd(
  onScrollNearEnd: (Unit) -> Unit
  ) = addOnScrollListener(object : RecyclerView.OnScrollListener() {
      override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        if (!YOUR_RECYCLER_VIEW.canScrollVertically(1)) {
          onScrollNearEnd(Unit)
            }
        }
    })

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