Home > database >  How to use SimpleOnGestureListener in custom view?
How to use SimpleOnGestureListener in custom view?

Time:06-02

I can't figure out how to use a gesture detector in a custom view. I want to useonLongPress, but I don't know where to put it or how to use it.

class CustomView(context: Context, attr: AttributeSet) : View(context, attr) {
   val listener = object :
        GestureDetector.SimpleOnGestureListener() {
      
        }
    }

   val detector = GestureDetector(context, listener)
}

Maybe someone can help me. Thank you.

CodePudding user response:

Have you read this? https://developer.android.com/training/gestures/detector#detect-all-supported-gestures

It's worth reading the whole thing, but basically you override the functions for the gestures you want to handle in your SimpleOnGestureListener

val listener = object : GestureDetector.SimpleOnGestureListener() {
    override fun onLongPress (MotionEvent e) {
        // do whatever
    }
}

Then you create a GestureDetector using that listener:

val detector = GestureDetectorCompat(context, listener)

then you override your view's onTouchEvent method and let your detector handle the events:

override fun onTouchEvent(event: MotionEvent): Boolean {
    detector.onTouchEvent(event)
    return super.onTouchEvent(event)
}
  • Related