拦截 View 触摸事件,判断滑动方向 March 22, 2024 7 - 复杂代码模版, 7.2 - 手势分发 本文总阅读量次 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657anyView.setOnTouchListener(object : View.OnTouchListener { private var initialX = 0f private var initialY = 0f private var hasScrolled = false override fun onTouch(v: View?, event: MotionEvent?): Boolean { event ?: return false when (event.action) { MotionEvent.ACTION_DOWN -> { // 记录初始触摸位置 initialX = event.x initialY = event.y hasScrolled = false } MotionEvent.ACTION_MOVE -> { if (!hasScrolled) { val diffX = event.x - initialX val diffY = event.y - initialY // 判断滑动方向,确保是水平滑动 if (abs(diffX) > abs(diffY)) { val direction = if (diffX < 0) Direction.LEFT else Direction.RIGHT handleHorizontalScroll(direction) hasScrolled = true } } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { hasScrolled = false } } return false } private fun handleHorizontalScroll(direction: Direction) { when (direction) { Direction.LEFT -> { // 向左滑动 showToast("发生向左滑动") // 在这里处理向左滑动的逻辑 } Direction.RIGHT -> { // 向右滑动 showToast("发生向右滑动") // 在这里处理向右滑动的逻辑 } } } private fun showToast(message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } enum class Direction { LEFT, RIGHT }} Newer TextView layout_constrainedWidth 属性 Older Android 性能专题 - 启动优化(一)启动耗时