Jaimin Modi
Jaimin Modi

Reputation: 1677

Kotlin - Scroll Detection issue in Recyclerview

Using below code to check that whether RecyclerView reached to bottom or not..

Means Checking that last item of the Recyclerview is visible or not..

For that I have googled and added Scroll listener in Recyclerview.

Using below code:

MyRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
       override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
           super.onScrollStateChanged(recyclerView, newState)
       }

       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
           super.onScrolled(recyclerView, dx, dy)
           if (!MyRecyclerView.canScrollVertically(1)) {
               Toast.makeText(mContext, "Last", Toast.LENGTH_LONG).show();
           }
       }
   })

Here, I am trying to check that Recyclerview reached to bottom or not.

Toast is not displaying when I scroll recyclerview to the bottom.

But, Toast displayed suddenly when items in the recyclerview binds first time. It should toast only when user scroll up to the bottom of the Recyclerview.

What might be the issue ? Please guide. Thanks.

Upvotes: 0

Views: 626

Answers (2)

Amit pandey
Amit pandey

Reputation: 1195

  rvPlayers?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            if (dy > 0) {
                if (isLastVisable()) {
                   //code here
                }
            }
        }
    })

 private fun isLastVisable(): Boolean {
    val layoutManager = rvPlayers.layoutManager as LinearLayoutManager
    val pos = layoutManager.findLastCompletelyVisibleItemPosition()
    val numItems = adapter.itemCount
    return (pos >= numItems - 1)
}

Upvotes: 0

Yrii Borodkin
Yrii Borodkin

Reputation: 782

I think, using RecyclerView.LayoutManager api will better suit your needs. You can check LinearLayoutManager::findLastCompletelyVisibleItemPosition or findLastVisibleItemPosition method in your RecyclerView.OnScrollListener

Upvotes: 1

Related Questions