Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if RecyclerView is scrolled on top (findFirstCompletelyVisibleItemPosition will not work)

How can i check if the recycler view is scrolled to its top (the begin of list) without using findFirstCompletelyVisibleItemPosition ?

Explanation: I cant use this method, because the items on RecyclerView are big and sometimes will never be "completely visible", so the method will return -1 (RecyclerView.NO_POSITION)

I need to know this to fire an action only when recycler view reach its top.

 val manager = timelineRecyclerView?.layoutManager as StaggeredGridLayoutManager
 val visibles = manager.findFirstCompletelyVisibleItemPositions(null)

Solved: Including some code to help

    timelineRecyclerView.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)

            currentTimelinePosition += dy

            Log.wtf("position", currentTimelinePosition.toString())
            //if the timeline position is on its start, allow swipe and refresh
            swipeLayout.isEnabled = currentTimelinePosition == 0
        }
    })
like image 328
cesarsicas Avatar asked Jan 04 '23 12:01

cesarsicas


1 Answers

You could create a RecyclerView.OnScrollListener, and keep track of how much it has scrolled.

For example, all you need to do is keep a variable, and update it with onScroll based on the vertical scroll amount.

class MyScrollListener() : RecyclerView.OnScrollListener() {

    var currentScrollPosition = 0

    override fun onScrolled(view: RecyclerView, dx: Int, dy: Int) {
        currentScrollPosition += dy

        if( currentScrollPosition == 0 ) {
            // We're at the top
        }
    }
}
like image 123
Advice-Dog Avatar answered Jan 06 '23 01:01

Advice-Dog