Android: ViewGroup, how to intercept a MotionEvent and then send to the target or eat it on demand?

Given that there is a ViewGroup with several children. Regarding this ViewGroup, I would like it to manage all of the MotionEvent for all of its children, which says that VG will 1. be able to intercept all events before they are sent to the target (children)
2. First, the VG consumes the event and determines whether the event will be further sent to the target child.
3. DOWN, MOVE, UP, I would like them to be relatively independent, which means that VG can eat DOWN, but give MOVE and UP to the children.

I read the UI Handling SDK guide, I knew event listeners, handlers, ViewGroup.onInterceptTouchEvent (MotionEvent) and View.onTouchEvent (MotionEvent).

Here is my example,

@Override public boolean onInterceptTouchEvent (MotionEvent event) { if (MotionEvent.ACTION_DOWN == event.getAction()) { return true; } return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (MotionEvent.ACTION_DOWN == event.getAction()) { return true; } else { if (!consumeEvent(event)) { // TODO: dispatch to target since I didn't want to eat event //return this.dispatchTouchEvent(event); // infinite loop!!! } } return super.onTouchEvent(event); } 

To be able to have some events, I must return true in both methods when the DOWN event occurred, because the SDK said so. Then I could see MOVE in onTouchEvent. However, in my case, I have no idea how to send events to children.

Above dispatchTouchEvent led to an infinite loop, which was understandable since VG itself could be the target. I can’t say which one will be targeted at that moment, MotionEvent didn’t give a hint, so dispatchTouchEvent was absolutely useless. Does anyone help me? Thanks.

+4
source share
1 answer

There is no easy way to find the View source from onInterceptTouchEvent , and there is no way to "send" these events. You can send KeyEvent s, but not MotionEvent s.

A common way to work with MotionEvent (for example, for dragging and dropping) is to handle MotionEvent.ACTION_DOWN events MotionEvent.ACTION_DOWN various View (via the onTouch after implementing OnTouchListener ), and MotionEvent.ACTION_MOVE through the parent Viewgroup method onInterceptTouchEvent .


But some LOCs say much more than a bunch of words. There is a very good example of what I am saying here: http://doandroids.com/blogs/tag/codeexample/


If you handle the ACTION_DOWN event in the view itself, you can save which view started it in another place and use this variable for further actions. An event is bound to the same view until it is completed by ACTION_UP or ACTION_CANCEL.

If you need to track a view and perform an action in a ViewGroup during ACTION_DOWN, I suggest you add a public method to your ViewGroup (e.g. public boolean handleActionDown (View v, MotionEvent e) that will be called from the onTouch callback

+4
source

All Articles