Android: onScrollStateChanged SCROLL_STATE_IDLE sometimes doesn't fire

前端 未结 3 1746
悲&欢浪女
悲&欢浪女 2021-02-05 23:00

I\'m running into a bit of a problem. What I\'m doing: I\'ve got a ListView which has got some images in it. To make the scrolling smoother I\'ve disabled the images to show up

3条回答
  •  轮回少年
    2021-02-05 23:23

    I ran into the same issue with a RecyclerView.

    Jason Burke's answer is correct, but I'll provide an alternate way of checking if you are at the beginning/end of the RecyclerView/ListView.

    I do it in onScrolled instead of onScrollStateChanged since I don't trust that I get a state changed event in the case when you scroll/fling to the edge of the RecyclerView.

    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
    
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                updateUi()
            }
        }
    
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
    
            /* If the user scrolls to the edges of the recyclerview, we can't trust that we get the SCROLL_STATE_IDLE state.
             * Therefore we have to update the view here in onScrolled for these cases
             */
            if (!recyclerView.canScrollVertically(1) || !recyclerView.canScrollVertically(-1)) {
                updateUi()
            }
        }
    }
    

    In my case it was actually a horizontal RecyclerView, so I had to do this instead:

    if (!recyclerView.canScrollHorizontally(1) || !recyclerView.canScrollHorizontally(-1)) {
        updateUi()
    }
    

提交回复
热议问题