2022-06-30

recycleView滑动监听加载更多

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:滑动到最后的监听
 */
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();//请求更多数据
        }
    }

    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"
                )
            }
        }
    }
    //取出数组中最大
    private fun findMax(intArray: IntArray): Int {
        var max = intArray[0]
        for (value in intArray) {
            if (value > max) {
                max = value
            }
        }
        return max
    }
}

你可能感兴趣的:(2022-06-30)