本文是android-api25版本的源码。
首先我们大概说一下事件机制的流程。
这里我们定义一个Activity,一个ViewgroupA,一个Myview来看看事件是如何传递的;
MainActivity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.e("TAG","MainActivity------dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("TAG","MainActivity------onTouchEvent");
return super.onTouchEvent(event);
}
}
ViewGroupA:
public class ViewGroupA extends LinearLayout {
public ViewGroupA(Context context, @Nullable AttributeSet attrs) {
super(context, attrs,0);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.e("TAG","ViewGroupA------dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.e("TAG","ViewGroupA------onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("TAG","ViewGroupA------onTouchEvent");
return super.onTouchEvent(event);
}
}
MyView:
public class MyView extends View {
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.e("TAG","MyView------dispatchTouchEvent");
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("TAG","MyView------onTouchEvent");
return super.onTouchEvent(event);
}
}
然后布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.mytestview.ViewGroupA
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:orientation="horizontal">
<com.example.mytestview.MyView
android:layout_width="100dp"
android:layout_height="200dp"
android:background="@android:color/holo_green_light"/>
com.example.mytestview.ViewGroupA>
LinearLayout>
以上可以说是非常简单的代码了,相信大家一看就懂,我们在MyView区域点击一下,看看输出:
com.example.mytestview E/TAG: MainActivity------dispatchTouchEvent
com.example.mytestview E/TAG: ViewGroupA------dispatchTouchEvent
com.example.mytestview E/TAG: ViewGroupA------onInterceptTouchEvent
com.example.mytestview E/TAG: MyView------dispatchTouchEvent
com.example.mytestview E/TAG: MyView------onTouchEvent
com.example.mytestview E/TAG: ViewGroupA------onTouchEvent
com.example.mytestview E/TAG: MainActivity------onTouchEvent
所以综上我们可以看出事件大概流程是如下这样的:
Activity->ViewGroup: dispatchTouchEvent
ViewGroup->ViewGroup: onInterceptTouchEvent
ViewGroup->View: dispatchTouchEvent
View-->ViewGroup: onTouchEvent
ViewGroup-->Activity: onTouchEvent
当然,有同学肯定会指出我上面的错误了:输出时候不是Viewgroup的dispatchTouchEvent先输出的吗?怎么到这里又变成onInterceptTouchEvent先执行了?不要坑我呀!
这里我就简单说明一下,的确是先执行的Viewgroup的dispatchTouchEvent方法的,但是在dispatchTouchEvent方法中首先就去调用了onInterceptTouchEvent方法去判断是否要拦截事件,后面我们看源码就知道了。图就只能先画成这样,有利大致理解。
好了,上面说了一下大致流程,接下来我们就来阅读源码了,深刻理解事件机制。
一步一步来,我们先看看Activity的diapatchTouchEvent:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
这里看出,getWindow即返回mWindow,而mWindow对应于PhoneWindow,然后我们看看PhoneWindow里面:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
如上,我们看出是调用了mDecor,mDecor对应的是DecorView,跟进去看看:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
到了这里,终于到我们熟悉的dispatchTouchEvent方法了,从我的另一篇文章Activity布局加载流程源码解析可以知道:DecorView是一个FrameLayout即ViewGroup,是Activity的最顶层根布局,由此我们从Activity进入到了Viewgroup。
我们马上来看看Viewgroup的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent ev) {
...
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
...
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//判断是否要禁止拦截,接着去调用onInterceptTouchEvent()方法
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
intercepted = true;
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
......
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
//判断子view能否收到点击事件,事件坐标是否在子view区域内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//获取新的触摸目标
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//dispatchTransformedTouchEvent()方法里面做了子view的事件分发
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
if (preorderedList != null) preorderedList.clear();
}
}
}
......
return handled;
}
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
···
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
//调用子组件分发事件
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
以上省略了部分代码;
viewgroup里面主要是做事件的分发,首先去调用onInterceptTouchEvent方法判断是否要拦截事件,然后就去查找子组件,并调用子组件的dispatchTouchEvent方法。如果没有子组件,就去调用super.dispatchTouchEvent()方法。
那接着代码走,我们看看view里面的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
view的这个dispatchTouchEvent方法不算太长,前面的暂且忽略,我们直接从第30行看起,这里看出,如果设置了触摸监听,那么onTouch方法是会先得到执行的。如果你在onTouch方法里面返回了true,那后面的onTouchEvent方法将不会得到执行。
36行去调用了onTouchEvent方法,如果onTouchEvent方法返回true,则接下来result会被赋值为true,最后返回的就是true,并一层一层往上返回。
接着我们马上来View里面看看onTouchEvent方法:
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
...
break;
case MotionEvent.ACTION_DOWN:
...
break;
case MotionEvent.ACTION_CANCEL:
...
break;
case MotionEvent.ACTION_MOVE:
...
break;
}
return true;
}
return false;
}
这里我缩减了很多代码,详细的请自行查阅源码。从以上代码我们可以看出如果当前view如果是可点击的,则直接返回true,事件在该view消费掉。如果是不可点击的就返回false,一旦返回false那后面的事件ACTION_MOVE和ACTION_UP将不会再传递到这里。
因此这里我们可以发现一个问题,如果你继承某个view,只收到了ACTION_DOWN事件,没有收到ACTION_MOVE和ACTION_UP事件,你只需要设置该view可点击即可(xml设置android:clickable="true"
)。
事件在这里到达最底层后,再一步步回溯到上层,上层再调用onTouchEvent方法。
另外再跟大家说一点,ViewGroup并没有实现onTouchEvent方法,哪它是在哪调用的onTouchEvent方法呢?
从ViewGroup源码里面看就知道,ViewGroup并没有实现onTouchEvent方法。然而ViewGroup是继承View的,只是它没有重写onTouchEvent方法而已,它是通过在dispatchTouchEvent中调用super.dispatchToucEvent()方法,而后它的父类(view)又调用了onTouchEvent方法,这一调用就回到viewgroup的onTouchEvent方法了。
我们最后再简单说一下事件分发流程,你点击屏幕,android手机会把点击事件首先从Activity传递到根布局decorView,然后便从这个根布局(ViewGroup)往下分发事件,直到遇到能处理该事件的view,如果没有处理该事件的view,到最底层后,就会沿着onTouchEvent方法往上回溯。