android事件处理涉及到的三个重要函数
事件分发:public boolean dispatchTouchEvent(MotionEvent ev)
由外部View接收,然后依次传递给其内层View
事件拦截:public boolean onInterceptTouchEvent(MotionEvent ev)
从最内View单元(事件源)开始依次向外层传递
事件响应:public boolean onTouchEvent(MotionEvent ev)
复杂性表现在:
可以控制每层事件是否继续传递(分发和拦截协同实现),以及事件的具体消费(事件分发也具有事件消费能力)。
三个函数所处位置
Activity 包含 dispatchTouchEvent
和 onTouchEvent
方法(API 25):
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
/**
* Called when a touch screen event was not handled by any of the views
* under it. This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
*
* @param event The touch screen event being processed.
*
* @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
ViewGroup包含dispatchTouchEvent
和onInterceptTouchEvent
方法。
View包含 dispatchTouchEvent
和 onTouchEvent
方法。
点击Button按钮时:
硬件触发
--> Activity示例(如LoginAcvtivity).dispatchTouchEvent --> Activity.dispatchTouchEvent
--> ViewGroup.dispatchTouchEvent --> ViewGroup.onInterceptTouchEvent
--> View.dispatchTouchEvent --> View.onTouchEvent
中间还有 DecorView.dispatchTouchEvent
,PhoneView.superDispatchTouchEvent
,DecorView.superDispatchTouchEvent
被触发,因为他们在Activity和ViewGrounp之间。
参考: