Posted at

Kotlin で EndlessScrollListener を書いてみました

More than 1 year has passed since last update.

このソースコード (gist) を読んだ後、

Kotlin に自分で変換してみようと思って書きました


Kotlin

abstract class EndlessScrollListener(private val layoutManager: LinearLayoutManager): RecyclerView.OnScrollListener() {

private var previousTotal = 0
private var loading = true
private var currentPage = 1
private var visibleThreshold = 0

private var visibleItemCount: Int = -1
private var totalItemCount: Int = -1
private var firstVisibleItem: Int = -1

override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)

visibleItemCount = recyclerView?.childCount ?: 0
totalItemCount = layoutManager.itemCount
firstVisibleItem = layoutManager.findFirstVisibleItemPosition()

if (loading) {
if (totalItemCount > previousTotal) {
loading = false
previousTotal = totalItemCount
}
}

if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
currentPage++
onLoadMore(currentPage)
loading = true
}
}

abstract fun onLoadMore(currentPage: Int)
}


使い方

Recycler view があるところに on scroll listener として追加します

// recyclerView は RecyclerView のインスタンス

// linearLayoutManager は LinearLayoutManager のインスタンス
recyclerView.addOnScrollListener(object : EndlessScrollListener(linearLayoutManager) {
override fun onLoadMore(currentPage: Int) {
Log.v("OnLoadMore", "page: $currentPage")
    }
})