检测 ViewPager2 中的过度滚动或页面结束事件 android

Detect overscroll or end of pages event in ViewPager2 android

ViewPager2 中没有过度滚动的方法我需要检测过度滚动,以便在没有更多页面时将用户带回主页。

ViewPager2 没有 public 方法来进行滚动,但是,可以通过监听 onPageScrollStateChanged

来检测

通常 onPageScrollStateChanged 中滚动状态的事件转换是 SCROLL_STATE_DRAGGING -> SCROLL_STATE_SETTLING -> SCROLL_STATE_IDLE 更改页面时

但是在过度滚动的情况下,序列是 SCROLL_STATE_DRAGGING -> SCROLL_STATE_IDLE

private fun listenOverScroll(currentIndex: Int, size: Int) {
        var index = currentIndex
        var previousState =  ViewPager2.SCROLL_STATE_IDLE
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                index = position
            }

            override fun onPageScrollStateChanged(state: Int) {
                Log.d(TAG,"Index:: $index | state:: $state | prevState:: $previousState")
                super.onPageScrollStateChanged(state)
                if ((index >= size - 1 || index <= 0)// end of list. these checks can be 
                                                     // used individualy to detect end or start of pages
                        && previousState == ViewPager2.SCROLL_STATE_DRAGGING // from DRAGGING
                        && state == ViewPager2.SCROLL_STATE_IDLE) {          // to IDLE
                    Log.d(TAG,"OVERSCROLL:: Index:: $index | state:: $state | prevState:: $previousState")
                    //overscroll performed. do your work here
                }
                previousState = state
            }
        })
    }