Android how can I get current positon on recyclerview that user scrolled to item

后端 未结 5 1473
清歌不尽
清歌不尽 2020-12-25 11:21

In my RecyclerView I have some items that user can scroll and see that. Now I want to save this position and scroll that after come back. This below code return

5条回答
  •  醉梦人生
    2020-12-25 12:06

    For a similar requirement plus some action needed to be performed on scroll state changed, I did this with a custom scroll listener:

    class OnScrollListener(private val action: () -> Unit) : RecyclerView.OnScrollListener() {
    
    private var actionExecuted: Boolean = false
    private var oldScrollPosition: Int = 0
    
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        when (newState) {
            RecyclerView.SCROLL_STATE_DRAGGING -> actionExecuted = false
            RecyclerView.SCROLL_STATE_SETTLING -> actionExecuted = false
            RecyclerView.SCROLL_STATE_IDLE -> {
    
                val scrolledPosition =
                    (recyclerView.layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition() ?: return
    
                if (scrolledPosition != RecyclerView.NO_POSITION && scrolledPosition != oldScrollPosition && !actionExecuted) {
                    action.invoke()
                    actionExecuted = true
                    oldScrollPosition = scrolledPosition
                }
    
            }
        }
    }
    

    }

    This is because of the pre-existing bug with RecyclerView onScroll which happens to trigger the callback 2-3 or even more times. And if there is some action to be performed, that will end up executing multiple times.

提交回复
热议问题