Last active
June 26, 2017 03:07
-
-
Save jutikorn/3b6afbf211ea08b3a45c49a1910bdaa0 to your computer and use it in GitHub Desktop.
Load more listener for RecyclerView
This file contains 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.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 | |
} | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From here: https://gist.github.com/ssinss/e06f12ef66c51252563e