Intercept Touch Events in a ViewGroup
The onInterceptTouchEvent()
method is called whenever a touch event is detected on the surface of a ViewGroup
, including on the surface of its children. If onInterceptTouchEvent()
return true, the MotionEvent
is intercepted, meaning it will not be passed on to the child, but rather to the onTouchEvent()
method of the parent.
Simply thinking of the process in code-presentation as follows:1
2
3
4
5
6
7
8public boolean dispatchTouchEvent(MotionEvent ev) {
if(!onInterceptTouchEvent()){
for(View child : children){
if(child.dispatchTouchEvent(ev))
return true;
}
}
return super.dispatchTouchEvent(ev);}
The onInterceptTouchEvent()
method gives a parent the chance to see any touch event before its children. If you return true from onInterceptTouchEvent()
the child view receives an ACTION_CANCEL and the events from that points forward are sent to parent’s onTouchEvent()
method for the usual handling.
onInterceptTouchEvent()
method can also return false and simply spy on events as the travel down the view hierarchy to their usual targets, which will handle the events with their own onTouchEvent()
.