Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.