Skip to content

Instantly share code, notes, and snippets.

@BasetEsmaeili
Last active January 3, 2021 08:24
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 BasetEsmaeili/37af250590618eda5690d6861d13d4a3 to your computer and use it in GitHub Desktop.
Save BasetEsmaeili/37af250590618eda5690d6861d13d4a3 to your computer and use it in GitHub Desktop.
Add Infinite Scroll to RecyclerView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
fun RecyclerView.attachInfiniteScroll(onLoadMoreListener: OnLoadMoreListener) {
if (layoutManager != null)
setInfiniteScrollGrid(this, layoutManager!!, onLoadMoreListener)
else throw RuntimeException("Layout Manager is Not Set")
}
/**
* this function get scrolling control of [.recyclerView] and whenever
* user reached list ends, [.onLoadMoreListener] will be called
*/
private fun setInfiniteScrollGrid(
recyclerView: RecyclerView,
layoutManager: RecyclerView.LayoutManager,
onLoadMoreListener: OnLoadMoreListener
) {
var totalItemCount = 0
var previousItemCount = 0
val threshold = 4
var lastVisibleItem = 0
var isLoading = false
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
totalItemCount = layoutManager.itemCount
if (previousItemCount > totalItemCount) {
previousItemCount = totalItemCount - threshold
}
when (layoutManager) {
is GridLayoutManager -> {
lastVisibleItem = layoutManager.findLastVisibleItemPosition()
}
is LinearLayoutManager -> {
lastVisibleItem = layoutManager.findLastVisibleItemPosition()
}
is StaggeredGridLayoutManager -> {
val spanCount = layoutManager.spanCount
val ids = IntArray(spanCount)
layoutManager.findLastVisibleItemPositions(ids)
var max = ids[0]
for (i in 1 until ids.size) {
if (ids[1] > max) {
max = ids[1]
}
}
lastVisibleItem = max
}
}
if (totalItemCount > threshold) {
if (previousItemCount <= totalItemCount && isLoading) {
isLoading = false
}
if (!isLoading && lastVisibleItem > totalItemCount - threshold && totalItemCount > previousItemCount) {
onLoadMoreListener.onLoadMore()
isLoading = true
previousItemCount = totalItemCount
}
}
super.onScrolled(recyclerView, dx, dy)
}
})
}
interface OnLoadMoreListener {
fun onLoadMore()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment