我有一个嵌套的 RecyclerView。我将它们称为 ParentRecyclerView 和 ChildRecyclerView。
我的目标有点复杂。
TouchEvent
)TouchEvent
)TouchEvent
。ChildRecyclerView获得TouchEvent
。)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
。 您可以修改 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)
}