Skip to content

Instantly share code, notes, and snippets.

@boyan01
Created March 6, 2018 08:13
Show Gist options
  • Save boyan01/4d93994e6e2b17c7d9d1f6ee71b3efa9 to your computer and use it in GitHub Desktop.
Save boyan01/4d93994e6e2b17c7d9d1f6ee71b3efa9 to your computer and use it in GitHub Desktop.
下滑自动加载更多
class LoadMoreDelegate(private val onLoadMoreListener: OnLoadMoreListener) {
fun attach(recyclerView: RecyclerView) {
recyclerView.addOnScrollListener(LoadMoreListener(onLoadMoreListener))
}
class LoadMoreListener(
private val onLoadMoreListener: OnLoadMoreListener) : RecyclerView.OnScrollListener() {
companion object {
private const val VISIBLE_THRESHOLD = 4
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (!onLoadMoreListener.canLoadMore) {
return
}
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val itemCount = layoutManager.itemCount
val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
val isBottom = VISIBLE_THRESHOLD > itemCount - lastVisiblePosition
if (isBottom) {
onLoadMoreListener.loadMore()
}
}
}
interface OnLoadMoreListener {
/**
* to check current is need to load more data
*/
val canLoadMore: Boolean
/**
* to load more data
*/
fun loadMore()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment