Last active
January 29, 2020 09:47
-
-
Save antonKozyriatskyi/1a822697cda45cca8ab62863ea480ada to your computer and use it in GitHub Desktop.
Load more listener for 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.LinearLayoutManager | |
import androidx.recyclerview.widget.RecyclerView | |
class LoadMoreListener( | |
private val threshold: Int, | |
private val listener: OnLoadMoreRequestedListener | |
) : RecyclerView.OnScrollListener() { | |
companion object { | |
fun attach( | |
threshold: Int, | |
recyclerView: RecyclerView, | |
listener: OnLoadMoreRequestedListener | |
) { | |
recyclerView.addOnScrollListener(LoadMoreListener(threshold, listener)) | |
} | |
} | |
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { | |
val isScrollingToBottom = dy > 0 | |
if (isScrollingToBottom) { | |
val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return | |
val lastIndex = layoutManager.itemCount - 1 | |
val lastVisiblePosition = layoutManager.findLastVisibleItemPosition() | |
val itemsToBottom = lastIndex - lastVisiblePosition | |
val thresholdMet = itemsToBottom <= threshold | |
if (thresholdMet) { | |
listener.onLoadMoreRequested() | |
} | |
} | |
} | |
interface OnLoadMoreRequestedListener { | |
fun onLoadMoreRequested() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment