Catch onTouch event by parent, handle it and pass to children

24,789

My understanding is that it actually goes the other direction. The Child views get their event triggered first (sort of). The root view get's it's dispatchTouchEvent() called, which propagates the event down to the children's onTouchEvent(), and then, depending on whether they return true or false, the parent's onTouchEvent() is called.

The normal solution for intercepting things like this is to override dispatchTouchEvent(MotionEvent ev) in one's activity like so:

@Override
public boolean dispatchTouchEvent (MotionEvent ev) {
  // Do your calcluations
  return super.dispatchTouchEvent(ev);
}

The documentation for this one is here. Note that you can also override that method in any ViewGroup (such as a FrameLayout, etc)

Share:
24,789
Elad92
Author by

Elad92

Updated on July 09, 2022

Comments

  • Elad92
    Elad92 almost 2 years

    I tried to understand how Android handle touch event and got a little bit confused. From what I understand touch event are send to the root view and pass down to the children. I have a FrameLayout that is a container for Fragment. First fragment view is a ScrollView, second one is some kind of Gallery (HorizontalListView) and the last one is also FrameLayout. Only one fragment in the layout each time. What I want to do is to identify user swipes on the screen, for the app use. I want to count the swipes and do something after some number of swipes.

    I tried to put a OnTouchListener on the top FrameLayout but it doesn't get called when the child is the ScrollView or the Gallery. I tried to return false and also true in the end of onTouch, but I get same result - it's never being called.

    How can I do it? I just want to "transparently" handle the touch events and passing them on like I didn't even touch them.

  • Elad92
    Elad92 over 11 years
    It worked! I extended FrameLayout, overrode the method you've mentioned, and sent the MotionEvent to a GestureDetector. All this subject is a little confusing. Thanks!
  • LOG_TAG
    LOG_TAG over 9 years
    @Elad92 like you mentioned can you help me to change this 2d scroll code? gist.github.com/LOG-TAG/0505eedccef9e00821da didn't getting how to send the MotionEvent to a GestureDetector
  • CrandellWS
    CrandellWS over 8 years
    so perhaps you would not use onTouchEvent(MotionEvent me) in the parent