Created
March 16, 2018 02:44
-
-
Save skydoves/a0b972131c7fe5baf2ddf3d8325f3c6a to your computer and use it in GitHub Desktop.
RecyclerViewPaginator
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
class RecyclerViewPaginator(val recyclerView: RecyclerView, | |
val isLoading: () -> Boolean, | |
val loadMore: (Int) -> Unit, | |
val onLast: () -> Boolean = { true }): RecyclerView.OnScrollListener() { | |
private val threshold = 10 | |
private var currentPage: Int = 0 | |
init { | |
recyclerView.addOnScrollListener(this) | |
} | |
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { | |
super.onScrolled(recyclerView, dx, dy) | |
val layoutManager = recyclerView.layoutManager | |
val visibleItemCount = recyclerView.layoutManager.childCount | |
val totalItemCount = recyclerView.layoutManager.itemCount | |
val firstVisibleItemPosition = when (layoutManager) { | |
is LinearLayoutManager -> layoutManager.findLastVisibleItemPosition() | |
is GridLayoutManager -> layoutManager.findLastVisibleItemPosition() | |
else -> return | |
} | |
if (onLast() || isLoading()) return | |
if ((visibleItemCount + firstVisibleItemPosition + threshold) >= totalItemCount) { | |
loadMore(++currentPage) | |
} | |
} | |
fun resetCurrentPage() { | |
this.currentPage = 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment