NestedRecyclerView 中分散 TouchEvent 的注意力

问题描述 投票:0回答:1

我有一个嵌套的 RecyclerView。我将它们称为 ParentRecyclerView 和 ChildRecyclerView。 我的目标有点复杂。

  1. 如果我点击ParentRecyclerView的item,那么ParentRecyclerView的item背景颜色将变为灰色。(这意味着ParentRecyclerView获得了
    TouchEvent
  2. 如果我点击ChildRecyclerView的item,那么效果与数字1相同。这意味着parentRecyclerview的item的颜色将变为灰色(点击/触摸,这意味着ParentRecyclerView像数字1一样获得
    TouchEvent
  3. 如果我触摸并水平拖动ChildRecyclerView,那么我可以滚动ChildRecyclerView。(这意味着ParentRecyclerView没有获得
    TouchEvent
    。ChildRecyclerView获得
    TouchEvent
    。)
    我使用带有 XML 的选择器来更改项目的背景。
    我使用
    TouchEvent
    使其按照我想要的方式工作,并进行了自定义
    ConstraintLayout

这是自定义ConstraintLayout的代码。

class TouchThroughConstraintLayout(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {
    private var mLastMotionX = 0f
    private var mLastMotionY = 0f

    private lateinit var childViewGroup: ViewGroup

    fun setChildView(childViewGroup: ViewGroup) { // in this case, the childViewGroup is ChildRecyclerView
        this.childViewGroup = childViewGroup
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mLastMotionX = ev.x
                mLastMotionY = ev.y
                return childViewGroup.isViewInBounds(ev.rawX.toInt(), ev.rawY.toInt())
            }

            MotionEvent.ACTION_MOVE -> {
                return false
            }
        }

        return false
    }

    private fun View.isViewInBounds(x : Int, y :Int): Boolean{
        val outRect = Rect()
        val location = IntArray(2)

        getDrawingRect(outRect)
        getLocationOnScreen(location)
        outRect.offset(location[0], location[1])

        return outRect.contains(x, y)
    }
}

但是代码不起作用,因为当我触摸childRecyclerView时,

isViewInBounds()
总是返回
true
。因此,ParentRecyclerView 获得了
TouchEvent

我该如何解决它?提前致谢。 :)

android android-recyclerview android-touch-event
1个回答
0
投票

您可以修改 isViewInBounds() 方法来检查触摸事件坐标是否落在子视图而不是父视图的边界内。检查这是否适合您。

private fun View.isViewInBounds(x: Int, y: Int): Boolean {
    val location = IntArray(2)
    getLocationOnScreen(location)

    val left = location[0]
    val top = location[1]
    val right = left + width
    val bottom = top + height

    val rect = Rect(left, top, right, bottom)
    return rect.contains(x, y)
  }
© www.soinside.com 2019 - 2024. All rights reserved.