32

I'm implementing a custom TextView and I want to do some action when the view is touched. I figured the onTouchEvent method would give me the full range of touches on the view without having to use setOnTouchListener (I'm trying to do all my work inside the view instead of in the activity so it's portable), but the only touch event registered is ACTION_DOWN. If I set an OnTouchListener in the activity using this, I get the full range of touch events, but onTouchEvent doesn't.

Anyone know why this is the case, or can anyone offer me a solution that doesn't involve using setOnTouchListener (Which would prevent the implementing activity from setting its own listener)?

Jonik
  • 80,077
  • 70
  • 264
  • 372
Jason Robinson
  • 31,005
  • 19
  • 77
  • 131

2 Answers2

78

You need to return true to get the following events after a down.

hackbod
  • 90,665
  • 16
  • 140
  • 154
  • 1
    If I do that, then any touch/click listeners applied from the activity never get triggered. I don't want to disable functionality. I just want to intercept any touches before they are dispatched, but still dispatch them. Calling `dispatchTouchEvent` just calls `onTouchEvent` again, causing a stack overflow (lol). – Jason Robinson Jun 17 '11 at 21:42
  • 2
    If you are in a ViewGroup container, you can override onInterceptTouchEvent() to monitor touch events being dispatched to your children. Besides that (or directly hooking in to dispatchTouchEvent -- not recommended), you can't do what you want. MotionEvent dispatching is based around finding a target via the first recipient who returns true and then dispatching all following events to that target. – hackbod Jun 23 '11 at 13:45
  • Fair enough. I guess what I need to know then is how to have a touch listener on a custom view that doesn't disallow the implementing class to have its own fully functional touch listener, but you've definitely answered the question in the title. – Jason Robinson Jun 23 '11 at 22:26
  • 1
    Why you don't simply put your "event monitor code" in the dispatchTouchEvent? @Override public boolean dispatchTouchEvent (MotionEvent ev) { //Monitor touch events here instead of inside the onTouchEvent, then dispatch them normally return super.dispatchTouchEvent(); } – Santacrab Apr 02 '15 at 09:45
1

return true on the onTouch() event. This mean we are still waiting on some new Actions from this event so other events like OnClick() is disabled.

On action ACTION_UP you need to return false at least to not get issues with other events after it.

niek tuytel
  • 899
  • 7
  • 18