Search code examples
androidtouch-eventgestures

In Android, when overriding touch events, why is a call to super.onTouchEvent(event) required?


In the tutorial at http://www.techotopia.com/index.php/Detecting_Common_Gestures_using_the_Android_Gesture_Detector_Class the author includes a call to the super.onTouchEvent(event) with a reminder to not forget it:

@Override 
public boolean onTouchEvent(MotionEvent event) { 
   this.gDetector.onTouchEvent(event);
   // Be sure to call the superclass implementation
   return super.onTouchEvent(event);
}

I am trying to figure out why this is necessary. In the example in that tutorial, I removed the call to the superclass and simply returned this.gDetector.onTouchEvent(event) and saw no change in the results.


Solution

  • From the Android source (Activity.java):

    public boolean onTouchEvent(MotionEvent event) {
      if (mWindow.shouldCloseOnTouch(this, event)) {
        finish();
        return true;
      }
      return false;
    }
    

    If you override this method and don't call super.onTouchEvent(event), then that code would not be executed. Most of the times you don't want that to happen, even if it doesn't seem to have any obvious effect.