Last active
January 3, 2021 08:24
-
-
Save BasetEsmaeili/37af250590618eda5690d6861d13d4a3 to your computer and use it in GitHub Desktop.
Add Infinite Scroll to 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
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