1、Activity---dispatchTouchEvent(MotionEvent ev)----这是APP的点击事件入口,用户的点击操作都是从activity的dispatchTouchEvent方法开始的。
某个activity
MainActivity
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
2、activity 的dispatchTouchEvent()方法的源码,最终走getWindow().superDispatchTouchEvent(ev)方法。getWindow()这个方法,返回mWindow,是Window的实例,Window 是抽象类,唯一实例是PhoneWindow
activity
/**
* 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);
}
3、再看PhoneWindow类中的superDispatchTouchEvent方法,最终走的mDecor的superDispatchTouchEvent,这个mDecor是DecorWindow的实例,DecorWindow是是FrameLayout的子类,最终也就走入到了viewgroup的DispatchTouchEvent方法了。
com.android.internal.policy.PhoneWindow
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
//mDecor 是DecorView的实例
}
com.android.internal.policy.DecorWindow 是FrameLayout的子类
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
//实际上执行的是ViewGroup的dispatchTouchEvent()方法
}
}
4、接着看viewgroup的dispatchTouchEvent分发,到这里大家基本都了解了,viewgroup会遍历包含的view,执行view的dispatchTouchEvent,这一部分的知识网上太多了,就不看源码了,想了解的自行百度。基本流程看图即可。
view的事件分发: