recycleView滑動(dòng)監(jiān)聽(tīng)加載更多
package com.pateo.online_video.app.follow.view
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import timber.log.Timber
/**
*Author:GianWang
*CreateTime:2022/6/28 下午3:59
*Description:滑動(dòng)到最后的監(jiān)聽(tīng)
*/
abstract class MyRecyclerOnScrollListener : RecyclerView.OnScrollListener() {
//加載更多
abstract fun onLoadMore()
var lastVisibleItemPosition = 0
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
var layoutManager = recyclerView.layoutManager
val visibleItemCount: Int = layoutManager!!.childCount
val totalItemCount: Int = layoutManager!!.itemCount
Timber.d("onScrollStateChanged $totalItemCount --- $visibleItemCount --- $lastVisibleItemPosition ")
if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItemPosition) >= totalItemCount - 1)) {
Timber.d("onScrollStateChanged loading more ")
onLoadMore();//請(qǐng)求更多數(shù)據(jù)
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
var layoutManager = recyclerView.layoutManager
when (layoutManager) {
is LinearLayoutManager -> {
lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
}
is GridLayoutManager -> {
lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
}
is StaggeredGridLayoutManager -> {
var ints = IntArray(layoutManager.spanCount)
ints = layoutManager.findLastCompletelyVisibleItemPositions(ints)
lastVisibleItemPosition = findMax(ints)
}
else -> {
throw RuntimeException(
"Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager"
)
}
}
}
//取出數(shù)組中最大
private fun findMax(intArray: IntArray): Int {
var max = intArray[0]
for (value in intArray) {
if (value > max) {
max = value
}
}
return max
}
}