Created
March 6, 2018 08:13
-
-
Save boyan01/4d93994e6e2b17c7d9d1f6ee71b3efa9 to your computer and use it in GitHub Desktop.
下滑自动加载更多
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
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