很多app的需求就有用RecycleView来实现,但是一般我们是从后端请求到RecycleView的数据,如何动态请求呢,即RecycleView下滑到底部时继续请求数据
private fun freshRecycleView() {
var isSliding: Boolean = false
rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
//dx为横向滚动 dy为竖向滚动
//如果为竖向滚动,则isSliding属性为true,横向滚动则为false
isSliding = dy > 0
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
//manager必须为LinearLayoutManager
val manager: LinearLayoutManager = rv.layoutManager as LinearLayoutManager
//newState是RecycleView的状态 如果它的状态为没有滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//获取最后一个完全显示的ItemPosition
val lastVisibleItem = manager.findLastCompletelyVisibleItemPosition()
//获取目前的item的数量
val totalItem = manager.itemCount
if (lastVisibleItem == (totalItem - 1)) {
//当滑动到最后一个时,加载更多数据
loadMoreData()
}
}
}
})
}
第一个函数onScrolled()是监听RecycleView的滚动方向
第二个函数onScrollStateChanged()是监听RecycleView滑动状态的改变
|