Fork me on GitHub

拦截 View 触摸事件,判断滑动方向

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
47
48
49
50
51
52
53
54
55
56
57
anyView.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
}
}
,