Created
October 3, 2020 21:52
-
-
Save farshadrezaee/c72edc0876f96a84f01e74040c637d02 to your computer and use it in GitHub Desktop.
Infinite scroll provider for recycler view
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
import androidx.recyclerview.widget.GridLayoutManager | |
import androidx.recyclerview.widget.LinearLayoutManager | |
import androidx.recyclerview.widget.RecyclerView | |
import androidx.recyclerview.widget.StaggeredGridLayoutManager | |
import kotlin.math.min | |
fun RecyclerView.onLoadMoreListener(onLoadMore: () -> Unit) { | |
this.addOnScrollListener(object : RecyclerView.OnScrollListener() { | |
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { | |
super.onScrolled(recyclerView, dx, dy) | |
if (dy < 0) return | |
if (layoutManager == null) return | |
val totalItemCount = layoutManager!!.itemCount | |
val visibleTotalCount = layoutManager!!.childCount | |
val firstVisibleItem = when (layoutManager) { | |
is GridLayoutManager -> { | |
(layoutManager as GridLayoutManager).findFirstVisibleItemPosition() | |
} | |
is LinearLayoutManager -> { | |
(layoutManager as LinearLayoutManager).findFirstVisibleItemPosition() | |
} | |
is StaggeredGridLayoutManager -> { | |
val staggeredGridLayoutManager = | |
layoutManager as StaggeredGridLayoutManager | |
val spanCount = staggeredGridLayoutManager.spanCount | |
val lastPositions = | |
staggeredGridLayoutManager.findFirstVisibleItemPositions(IntArray(spanCount)) | |
Math.min(lastPositions[0], lastPositions[1]) | |
} | |
else -> 0 | |
} | |
if (totalItemCount <= visibleTotalCount) { | |
return | |
} | |
if (firstVisibleItem + visibleTotalCount >= totalItemCount) { | |
recyclerView.post { | |
onLoadMore() | |
} | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment