RecyclerView Item 嵌套 ScrollView 产生 Touch 事件冲突,通过自定义ScrollView来拦截和处理事件
自定义 ItemScrollView
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.widget.ScrollView
class ItemScrollView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ScrollView(context, attrs, defStyleAttr) {
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { parent.requestDisallowInterceptTouchEvent(true) return super.onInterceptTouchEvent(ev) }
private var lastY: Float = 0f
override fun onTouchEvent(ev: MotionEvent?): Boolean { when (ev?.action) { MotionEvent.ACTION_DOWN -> { lastY = ev.y }
MotionEvent.ACTION_MOVE -> { val currentY = ev.y this.scrollBy(0, (lastY - currentY).toInt()) lastY = currentY }
MotionEvent.ACTION_UP -> { lastY = 0f } }
return canScroll() }
private fun canScroll(): Boolean { val child = getChildAt(0) child?.let { return height < child.height } return false } }
|