我的横向RecyclerView
包含leftPadding = 48dp
,topPadding = 24dp
和clipToPadding = false
。它从左侧的空白区域开始,但是当用户滚动列表时,其项目将在该(先前为空)空间上绘制。顶部空格总是空的。
此RecyclerView
位于带有foreground = selectableItemBackground
的FrameLayout内。
我的问题来自RecyclerView
消耗并忽略左侧和顶部空格上的触摸,这意味着OnClickListener
不会被触发,这两者都附加到{{1} }或FrameLayout
。
我已尝试使用RecyclerView
和clickable = false
focusable = false
,但它无效。
我在寻找:
RecyclerView
RecyclerView
项
RecyclerView
空格时FrameLayout
点击事件RecyclerView's
个空格
编辑:我创建了一个简单的项目,显示我正在谈论的问题:https://github.com/dadino/recyclerviewemptyspacestest 有两个提交,第一个我试图抓住父视图的点击,第二个我试图抓住RecyclerView本身的点击。它们都不起作用。
答案 0 :(得分:13)
您必须创建自定义RecyclerView
实施,您可以在其中收听触摸事件并根据该事件执行过滤。
class MyRecyclerView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
private var isValid = false
private var x: Int = 0
private var y: Int = 0
// this will help us to understand whether the event can be considered a touch or scroll
private val delta: Int = ViewConfiguration.get(getContext()).scaledTouchSlop
override fun onTouchEvent(e: MotionEvent?): Boolean {
val onTouchEvent = super.onTouchEvent(e)
when (e?.action) {
MotionEvent.ACTION_DOWN -> {
// saving initial touch location
x = e.rawX.toInt()
y = e.rawY.toInt()
isValid = true
}
MotionEvent.ACTION_MOVE -> {
if (Math.abs(e.rawX - x) > delta ||
Math.abs(e.rawY - y) > delta) {
// if a scroll happens - no longer consider this movement as valid
// this is needed for handling scroll on the inner part of `RecyclerView`
isValid = false
}
}
MotionEvent.ACTION_UP -> {
if (isValid && Math.abs(e.rawX - x) < delta &&
Math.abs(e.rawY - y) < delta &&
isInRightArea(e)) {
// 1. if the movement is still valid
// 2. we have actually performed a click
// 3. the click is in expected rectangle
// then perform click
performClick()
}
}
}
return onTouchEvent
}
// This is needed in order to handle the edge case, when a click listener
// would be fired when performing a click between the items of `RecyclerView`
private fun isInRightArea(e: MotionEvent): Boolean {
val r = Rect()
getGlobalVisibleRect(r)
r.left = paddingLeft
r.top = r.top + paddingTop
return !r.contains(e.rawX.toInt(), e.rawY.toInt())
}
}
结果: