Created
September 5, 2017 02:08
-
-
Save maxost/be029008600680232984c49d9d1b681b to your computer and use it in GitHub Desktop.
Kotlin: RecyclerView assign on scroll to end listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
}) |
kotlin beginner: would love to see an example of how this could be used..
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
Can you show me a example usage of this?