java fragment example - Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?





7 Answers

Because this is the first result on Google. I want to share with you a great Talk by Dave Smith on Youtube: Mastering the Android Touch System and the slides are available here. It gave me a good deep understanding about the Android Touch System:

How the Activity handles touch:

  • Activity.dispatchTouchEvent()
    • Always first to be called
    • Sends event to root view attached to Window
    • onTouchEvent()
      • Called if no views consume the event
      • Always last to be called

How the View handles touch:

  • View.dispatchTouchEvent()
    • Sends event to listener first, if exists
      • View.OnTouchListener.onTouch()
    • If not consumed, processes the touch itself
      • View.onTouchEvent()

How a ViewGroup handles touch:

  • ViewGroup.dispatchTouchEvent()
    • onInterceptTouchEvent()
      • Check if it should supersede children
      • Passes ACTION_CANCEL to active child
      • Return true once, consumes all subsequent events
    • For each child view, in reverse order they were added
      • If touch is relevant (inside view), child.dispatchTouchEvent()
      • If not handled by previous, dispatch to next view
    • If no children handle event, listener gets a chance
      • OnTouchListener.onTouch()
    • If no listener, or not handled
      • onTouchEvent()
  • Intercepted events jump over child step

He also provides example code of custom touch on github.com/devunwired/.

Answer: Basically the dispatchTouchEvent() is called on every View layer to determine if a View is interested in an ongoing gesture. In a ViewGroup the ViewGroup has the ability to steal the touch events in his dispatchTouchEvent()-method, before it would call dispatchTouchEvent() on the children. The ViewGroup would only stop the dispatching if the ViewGroup onInterceptTouchEvent()-method returns true. The difference is that dispatchTouchEvent()is dispatching MotionEvents and onInterceptTouchEvent tells if it should intercept (not dispatching the MotionEvent to children) or not (dispatching to children).

You could imagine the code of a ViewGroup doing more-or-less this (very simplified):

public boolean dispatchTouchEvent(MotionEvent ev) {
    if(!onInterceptTouchEvent()){
        for(View child : children){
            if(child.dispatchTouchEvent(ev))
                return true;
        }
    }
    return super.dispatchTouchEvent(ev);
}
recyclerview not working

What is the difference between onInterceptTouchEvent and dispatchTouchEvent in Android?

According to the android developer guide, both methods can be used to intercept a touch event (MotionEvent), but what is the difference?

How do onInterceptTouchEvent, dispatchTouchEvent and onTouchEvent interact together within a hierarchy of Views (ViewGroup)?




There is a lot of confusion about these methods, but it is actually not that complicated. Most of the confusion is because:

  1. If your View/ViewGroup or any of its children do not return true in onTouchEvent, dispatchTouchEvent and onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN. Without a true from onTouchEvent, the parent view will assume your view does not need the MotionEvents.
  2. When none of the children of a ViewGroup return true in onTouchEvent, onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN, even if your ViewGroup returns true in onTouchEvent.

Processing order is like this:

  1. dispatchTouchEvent is called.
  2. onInterceptTouchEvent is called for MotionEvent.ACTION_DOWN or when any of the children of the ViewGroup returned true in onTouchEvent.
  3. onTouchEvent is first called on the children of the ViewGroup and when none of the children returns true it is called on the View/ViewGroup.

If you want to preview TouchEvents/MotionEvents without disabling the events on your children, you must do two things:

  1. Override dispatchTouchEvent to preview the event and return super.dispatchTouchEvent(ev);
  2. Override onTouchEvent and return true, otherwise you won’t get any MotionEvent except MotionEvent.ACTION_DOWN.

If you want to detect some gesture like a swipe event, without disabling other events on your children as long as you did not detect the gesture, you can do it like this:

  1. Preview the MotionEvents as described above and set a flag when you detected your gesture.
  2. Return true in onInterceptTouchEvent when your flag is set to cancel MotionEvent processing by your children. This is also a convenient place to reset your flag, because onInterceptTouchEvent won’t be called again until the next MotionEvent.ACTION_DOWN.

Example of overrides in a FrameLayout (my example in is C# as I’m programming with Xamarin Android, but the logic is the same in Java):

public override bool DispatchTouchEvent(MotionEvent e)
{
    // Preview the touch event to detect a swipe:
    switch (e.ActionMasked)
    {
        case MotionEventActions.Down:
            _processingSwipe = false;
            _touchStartPosition = e.RawX;
            break;
        case MotionEventActions.Move:
            if (!_processingSwipe)
            {
                float move = e.RawX - _touchStartPosition;
                if (move >= _swipeSize)
                {
                    _processingSwipe = true;
                    _cancelChildren = true;
                    ProcessSwipe();
                }
            }
            break;
    }
    return base.DispatchTouchEvent(e);
}

public override bool OnTouchEvent(MotionEvent e)
{
    // To make sure to receive touch events, tell parent we are handling them:
    return true;
}

public override bool OnInterceptTouchEvent(MotionEvent e)
{
    // Cancel all children when processing a swipe:
    if (_cancelChildren)
    {
        // Reset cancel flag here, as OnInterceptTouchEvent won't be called until the next MotionEventActions.Down:
        _cancelChildren = false;
        return true;
    }
    return false;
}



dispatchTouchEvent handles before onInterceptTouchEvent.

Using this simple example:

   main = new LinearLayout(this){
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            System.out.println("Event - onInterceptTouchEvent");
            return super.onInterceptTouchEvent(ev);
            //return false; //event get propagated
        }
        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            System.out.println("Event - dispatchTouchEvent");
            return super.dispatchTouchEvent(ev);
            //return false; //event DONT get propagated
        }
    };

    main.setBackgroundColor(Color.GRAY);
    main.setLayoutParams(new LinearLayout.LayoutParams(320,480));    


    viewA = new EditText(this);
    viewA.setBackgroundColor(Color.YELLOW);
    viewA.setTextColor(Color.BLACK);
    viewA.setTextSize(16);
    viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80));
    main.addView(viewA);

    setContentView(main);

You can see that the log willl be like:

I/System.out(25900): Event - dispatchTouchEvent
I/System.out(25900): Event - onInterceptTouchEvent

So in case you are working with these 2 handlers use dispatchTouchEvent to handle on first instance the event, which will go to onInterceptTouchEvent.

Another difference is that if dispatchTouchEvent return 'false' the event dont get propagated to the child, in this case the EditText, whereas if you return false in onInterceptTouchEvent the event still get dispatch to the EditText




The following code within a ViewGroup subclass would prevent it's parent containers from receiving touch events:

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    // Normal event dispatch to this container's children, ignore the return value
    super.dispatchTouchEvent(ev);

    // Always consume the event so it is not dispatched further up the chain
    return true;
  }

I used this with a custom overlay to prevent background views from responding to touch events.




ViewGroup's onInterceptTouchEvent() is always the entry point for ACTION_DOWN event which is first event to occur.

If you want ViewGroup to process this gesture, return true from onInterceptTouchEvent(). On returning true, ViewGroup's onTouchEvent() will receive all subsequent events till next ACTION_UP or ACTION_CANCEL, and in most cases, the touch events between ACTION_DOWN and ACTION_UP or ACTION_CANCEL are ACTION_MOVE, which will normally be recognized as scrolling/fling gestures.

If you return false from onInterceptTouchEvent(), the target view's onTouchEvent() will be called. It will be repeated for subsequent messages till you return true from onInterceptTouchEvent().

Source: http://neevek.net/posts/2013/10/13/implementing-onInterceptTouchEvent-and-onTouchEvent-for-ViewGroup.html




Both Activity and View have method dispatchTouchEvent() and onTouchEvent.The ViewGroup have this methods too, but have another method called onInterceptTouchEvent. The return type of those methods are boolean, you can control the dispatch route through the return value.

The event dispatch in Android starts from Activity->ViewGroup->View.




Small answer:

onInterceptTouchEvent comes before setOnTouchListener.




Related