Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fcannizzaro
Last active August 28, 2017 10: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 fcannizzaro/9e3f7e51e80ab1c6bb69e05a90d87071 to your computer and use it in GitHub Desktop.
Save fcannizzaro/9e3f7e51e80ab1c6bb69e05a90d87071 to your computer and use it in GitHub Desktop.
Kotlin version of ssinss's EndlessRecyclerOnScrollListener (https://gist.github.com/ssinss/e06f12ef66c51252563e)
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import kotlin.properties.Delegates
class InfiniteScroll(private var layoutManager: LinearLayoutManager, private var loadMore: (page: Int) -> Unit) : RecyclerView.OnScrollListener() {
private var loading = true
private var previousTotal = 0
private var visibleThreshold = 5
private var current_page = 1
private var firstVisibleItem by Delegates.notNull<Int>()
private var visibleItemCount by Delegates.notNull<Int>()
private var totalItemCount by Delegates.notNull<Int>()
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
visibleItemCount = recyclerView.childCount
totalItemCount = layoutManager.itemCount
firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (totalItemCount > previousTotal) {
loading = false
previousTotal = totalItemCount
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
loadMore(++current_page)
loading = true
}
}
}
val list = RecyclerView(this)
val layoutManager = LinearLayoutManager(this)
list.layoutManager = layoutManager
list.addOnScrollListener(InfiniteScroll(layoutManager) {
println("load page $it")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment