到达终点时如何以编程方式取消RecyclerView上的猛扑

时间:2019-06-04 21:02:27

标签: android android-recyclerview android-coordinatorlayout

我正在CoordinatorLayout中使用ViewPager,并在其每个页面中都带有RecyclerViews(以small sample project on GitHub进行演示)。我注意到,在逃到RecyclerView的末尾之后,在ViewPager中向左/向右滑动已被忽略了一段时间。缩小问题范围,我得出的结论(实际上是一种假设)是,在到达RecyclerView的末尾后,猛击仍持续了一段时间(相当短的时间),只有在此之后才能在ViewPager上滑动逃跑已经停止。

以下是该问题的演示gif:只有滚动才能使ViewPager立即滑动,而滑动则需要2次尝试(或仅需要一段时间)。

img

是否有一种干净的方法来阻止猛扑到RecyclerView的任一端?我的解决方法是在到达末尾时调度MotionEvent,但这感觉很黑。

1 个答案:

答案 0 :(得分:0)

我设法通过如下子类化RecyclerView来解决此问题(当然,仍然可以接受其他建议):

/**
 * RecyclerView dispatching an ACTION_DOWN MotionEvent when reaching either its beginning
 * or end and consuming a fling gesture when that fling is in the (vertical) direction
 * the RecyclerView can't scroll anymore anyway.
 *
 * Background: in following setup
 *
 *  <CoordinatorLayout>
 *      <NestedScrollView>
 *          <ViewPager>
 *              <Fragments containing RecyclerView/>
 *          </ViewPager>
 *      </NestedScrollView>
 *  </CoordinatorLayout>
 *
 * a vertical fling on the RecyclerView will prevent the viewpager to swipe right/left
 * immediately after reaching the end (on scroll down) or beginning (on scroll up) of the RV.
 * It seems the RV is intercepting the touch until the fling has worn off. TouchyRecyclerView
 * is a workaround for this phenomenon by both
 *  a) cancelling the fling on reaching either end of the RecyclerView by dispatching a
 *     MotionEvent ACTION_DOWN and
 *  b) consuming a detected fling gesture when that fling is in the direction the RV is
 *     at the respective end.
 */
class TouchyRecyclerView : RecyclerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

    private val gestureDetector: GestureDetector by lazy {
        GestureDetector(context, VerticalFlingListener(this))
    }
    private val scrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val llm: LinearLayoutManager = recyclerView.layoutManager as LinearLayoutManager

            if (dy > 0) { // we're scrolling down the RecyclerView
                val adapter = adapter
                val position = llm.findLastCompletelyVisibleItemPosition()
                if (adapter != null && position == adapter.itemCount - 1) {
                    // and we're at the bottom
                    dispatchActionDownMotionEvent()
                }
            } else if (dy < 0) { // we're scrolling up the RecyclerView
                val position = llm.findFirstCompletelyVisibleItemPosition()
                if (position == 0) {
                    // and we're at the very top
                    dispatchActionDownMotionEvent()
                }
            }
        }
    }

    init {
        this.addOnScrollListener(scrollListener)
    }

    private fun dispatchActionDownMotionEvent() {
        val los = intArrayOf(0, 0)
        this.getLocationOnScreen(los)
        val e = MotionEvent.obtain(
            0,
            0,
            ACTION_DOWN,
            los[0].toFloat(),
            los[1].toFloat(),
            0)
        dispatchTouchEvent(e)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(e: MotionEvent?): Boolean {
        return if (gestureDetector.onTouchEvent(e)) {
            true
        } else {
            super.onTouchEvent(e)
        }
    }

    /**
     * Listener to consume unnecessary vertical flings (i.e. when the RecyclerView is at the respective end).
     */
    inner class VerticalFlingListener(private val recyclerView: RecyclerView) :
        GestureDetector.SimpleOnGestureListener() {
        override fun onDown(e: MotionEvent?): Boolean {
            return true
        }

        override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
            val adapter = recyclerView.adapter
            val llm = recyclerView.layoutManager as LinearLayoutManager
            if (velocityY < 0) { // we're flinging down the RecyclerView
                if (adapter != null &&
                    llm.findLastCompletelyVisibleItemPosition() == adapter.itemCount - 1) {
                    // but we're already at the bottom - consume the fling
                    return true
                }
            } else if (velocityY > 0) { // we're flinging up the RecyclerView
                if (0 == llm.findFirstCompletelyVisibleItemPosition()) {
                    // but we're already at the top - consume the fling
                    return true
                }
            }
            return false
        }
    }
}