I'm trying to implement a gesture detector for my application written in Kotlin. I'm following the comment on this question: link
So, I created the OnSwipeTouchListener class and I implemented the listener in my class:
class DetailActivity : AppCompatActivity() {
override fun onBackPressed() {
super.onBackPressed()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.detail_activity)
window.decorView.setOnTouchListener(object: OnSwipeTouchListener(this@DetailActivity) {
override fun onSwipeLeft() {
onBackPressed()
}
override fun onSwipeRight() {
onBackPressed()
}
})
}
The problem is that it doesn't get recognized and I don't get any error. I tried to put a Log.i to check if the program enters in the two overrides methods, but nothing get printed. Can it be a View problem?
EDIT: this is the Listener code:
open class OnSwipeTouchListener(ctx: Context) : 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 {
return gestureDetector.onTouchEvent(event)
}
private inner class GestureListener : 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() {}
}
onTouchListener
to the decor view can be a problem. Have you tried settingOnSwipeTouchListener
on your activity root view or other view? – Kanpur