30 August, 2013

View.OnTouchListener vs. View.onTouchEvent

View.OnTouchListener

View myView = findViewById(R.id.my_view); 

myView.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {

        // ... Respond to touch events       

        return true;

    }

})

Beware of creating a listener that returns false for the ACTION_DOWN event. If you do this, the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events. This is because ACTION_DOWN is the starting point for all touch events. --from android developer site.


How to understand:

Above referred note is not exactly correct.

First, what is the OnTouchListener:

Interface definition for a callback to be invoked when a touch event is dispatched to this view. The callback will be invoked before the touch event is given to the view.

Please take notice on the bold text.

Return false means to dispatch the event to view's onTouchEvent method.

Return true means to handle the event and do not dispatch the event to view's onTouchEvent method. That will not affect the subsequent event.

 

View.onTouchEvent

Implement this method to handle touch screen motion events.

Return true if the event was handled, false otherwise

Please notice:

If return false when the action is ACTION_DOWN, that means the event will propagate to parent view, and let parent view handle events including the subsequent events.The view will not receive any events any more.

when return true, that means the event is handled, and view is waiting for next event.

The final onTouchEvent is of the activity layer, which will handle all unhandled events.