1. SwipePage.kt
SWIPE_THRESHOLD는 X좌표 동작 기준값, SWIPE_VELOCITY_THRESHOLD는 Y좌표 동작 기준값.
개인적으로 엄지손가락으로 살짝 스와이프 하여도 동작되기 위해서는 X = 50, Y = 20 정도로 세팅
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
58
59
60
61
62
63
64
65
| import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
open class OnSwipeTouchListener(ctx: Context) : View.OnTouchListener {
private val gestureDetector: GestureDetector
companion object {
private val SWIPE_THRESHOLD = 100
private val SWIPE_VELOCITY_THRESHOLD = 100
}
init {
gestureDetector = GestureDetector(ctx, GestureListener())
}
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
try {
return gestureDetector.onTouchEvent(event)
} catch (e: Exception) {
// Error Handling
}
return false
}
private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
var result = false
try {
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight()
} else {
onSwipeLeft()
}
result = true
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD){
if (diffY > 0) {
onSwipeBottom()
} else {
onSwipeTop()
}
result = true
}
} catch (exception: Exception) {
exception.printStackTrace()
}
return result
}
}
open fun onSwipeRight() {}
open fun onSwipeLeft() {}
open fun onSwipeTop() {}
open fun onSwipeBottom() {}
}
|
2. MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| SampleLayoutView1.setOnTouchListener(object: OnSwipeTouchListener(this@MainActivity) {
override fun onSwipeLeft() {
Toast.makeText(this@MainActivity,"왼쪽으로",Toast.LENGTH_SHORT).show()
}
override fun onSwipeRight() {
Toast.makeText(this@MainActivity,"오른쪽으로",Toast.LENGTH_SHORT).show()
}
override fun onSwipeTop() {
Toast.makeText(this@MainActivity,"위로",Toast.LENGTH_SHORT).show()
}
override fun onSwipeBottom() {
Toast.makeText(this@MainActivity,"아래로",Toast.LENGTH_SHORT).show()
}
})
|