ViewPager2 嵌套 ViewPager2 解决方案

最近新业务要求,在ViewPager2 的item中,再放一个ViewPager2用来展示Banner效果。发现两个嵌套之后,内部的ViewPager2无法滑动,首先考虑的就是滑动冲突,打算重写ViewPager2,修改onInterceptTouchEvent方法。却发现ViewPager2是final修饰,无法继承重写。只能考虑别的方法。

后来,在ViewPager2官方文档中找到这么不起眼的一小段

32589F60-E0E4-4757-9FCB-E3EA7EA419EE.png

大致意思就是:ViewPager2 嵌套在相同方向的滚动View中是不能滚动的,如果需要滚动ViewPager2,就需要调用requestDisallowInterceptTouchEvent,才可以接受到滑动事件。
而且Google还给出了方案:views-widgets-samples/NestedScrollableHost.kt at master · android/views-widgets-samples · GitHub

我把代码也贴出来,简单看下原理

/**
 * Layout to wrap a scrollable component inside a ViewPager2. Provided as a solution to the problem
 * where pages of ViewPager2 have nested scrollable elements that scroll in the same direction as
 * ViewPager2. The scrollable element needs to be the immediate and only child of this host layout.
 *
 * This solution has limitations when using multiple levels of nested scrollable elements
 * (e.g. a horizontal RecyclerView in a vertical RecyclerView in a horizontal ViewPager2).
 */

class NestedScrollableHost : FrameLayout {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    private var touchSlop = 0
    private var initialX = 0f
    private var initialY = 0f

    private val parentViewPager: ViewPager2?
        get() {
            var v: View? = parent as? View
            while (v != null && v !is ViewPager2) {
                v = v.parent as? View
            }
            return v as? ViewPager2
        }

    private val child: View? get() = if (childCount > 0) getChildAt(0) else null

    init {
        touchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    private fun canChildScroll(orientation: Int, delta: Float): Boolean {
        val direction = -delta.sign.toInt()
        return when (orientation) {
            0 -> child?.canScrollHorizontally(direction) ?: false
            1 -> child?.canScrollVertically(direction) ?: false
            else -> throw IllegalArgumentException()
        }
    }

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        handleInterceptTouchEvent(e)
        return super.onInterceptTouchEvent(e)
    }

    private fun handleInterceptTouchEvent(e: MotionEvent) {
        val orientation = parentViewPager?.orientation ?: return
        // Early return if child can't scroll in same direction as parent
        if (!canChildScroll(orientation, -1f) && !canChildScroll(orientation, 1f)) {
            return
        }

        if (e.action == MotionEvent.ACTION_DOWN) {
            initialX = e.x
            initialY = e.y
            parent.requestDisallowInterceptTouchEvent(true)
        } else if (e.action == MotionEvent.ACTION_MOVE) {
            val dx = e.x - initialX
            val dy = e.y - initialY
            val isVpHorizontal = orientation == ORIENTATION_HORIZONTAL
            // assuming ViewPager2 touch-slop is 2x touch-slop of child
            val scaledDx = dx.absoluteValue * if (isVpHorizontal) .5f else 1f
            val scaledDy = dy.absoluteValue * if (isVpHorizontal) 1f else .5f

            if (scaledDx > touchSlop || scaledDy > touchSlop) {

                if (isVpHorizontal == (scaledDy > scaledDx)) {
                    // Gesture is perpendicular, allow all parents to intercept
                    parent.requestDisallowInterceptTouchEvent(false)
                } else {
                    // Gesture is parallel, query child if movement in that direction is possible
                    if (canChildScroll(orientation, if (isVpHorizontal) dx else dy)) {
                        // Child can scroll, disallow all parents to intercept
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else {
                        // Child cannot scroll, allow all parents to intercept
                        parent.requestDisallowInterceptTouchEvent(false)
                    }
                }
            }
        }
    }
}

用法也很简单,用NestedScrollableHost把内部ViewPager2包裹起来就可以啦。

我们主动包裹住内部ViewPager2后,就代表着需要处理事件了,所以在onInterceptTouchEvent函数中,如果接受到了DOWN事件,就需要调用requestDisallowInterceptTouchEvent通知外层的ViewPager2不要拦截事件,让我们的Host来处理滑动事件。

等到MOVE事件进来后,判断一下能不能顺着手势滑动内部的ViewPager2?
不能就不给内部ViewPager2后续事件了(主动通知外部ViewPager2拦截事件)。

Host的作用就相当于是一个开关在两个ViewPager2之间。当内部的还可以滑动,就允许事件传递下去,当内部无法在手势方向滑动,就通知外部View进行事件拦截。

完美解决了ViewPager2的嵌套问题。

按照这一思想,对于好多滑动冲突的问题,都可以不用继承,直接写一个Host来解决嵌套问题

你可能感兴趣的:(ViewPager2 嵌套 ViewPager2 解决方案)