Android事件对象MotionEvent,是指在手触摸屏幕后所产生的一系列事件,其中典型的三种:
ACTION_DOWN、ACTION_MOVE、ACTION_UP;
通常情况下事件都是以ACTION_DOWN开始,ACTION_UP结束。
View的事件分发过程也就是MotionEvent的分发过程;
先借图说话:
事件分发主要由三个方法完成:
dispatchTouchEvent() :进行事件分发,如果事件能够传递给当前view,此方法一定被调用
onInterceptTouchEvent():在dispatchTouchEvent方法内部,用来判断是否拦截某个事件
onTouchEvent():在dispatchTouchEvent方法中调用,用来处理点击事件
事件分发总是按顺序从:Acivity ——> ViewGroup ——> View;默认情况下,事件是可以直接传递到最上层View,如果此时最上层View返回false,即不处理,那么父容器的onTouchEvent将会被调用,依次类推,如果都不处理,最终会传递回给Activity的onTouchEvent方法处理;
结合源码分析事件传递:
首先看到Activity的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
onUserInteracthion()方法是空方法,可以不用管;
看到第二个判断,getWindow().superDispatchTouchEvent(ev),因为window的一个抽象类,唯一实现是PhoneWindow,在PhoneWindow找到具体实现:
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
其中mDecor是一个DecorView,继续跟进到DecorView的superDispatchTouchEvent方法:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
调用了父类的dispatchTouchEvent方法,因为DecorView是继承自FrameLayout,最终事件传递到了ViewGroup中去处理
在回过来看onTouchEvent方法
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
其中mWindow.shouldCloseOnTouch(this, event)方法判断是否是DOWN事件,event的坐标是否在边界内等;返回true这说明事件在边界外,即事件消费了;返回false未消费.
总结:当一个事件产生时,从Activity开始分发,传递到PhoneWindow,PhoneWindow又传递到DecorView,DecorView最终调用父类的dispatchTouchEvent方法,到这就传递到了ViewGroup;
接下来看ViewGroup的dispatchTouchEvent方法:
关键部分代码:
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
首先判断如果是ACTION_DOWN事件,则进行初始化,因为事件都是由ACTION_DOWN开始的,如果是ACTION_DOWN事件,则表示这是一个新的事件序列;
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
这段代码判断是否需要拦截,在事件为ACTION_DOWN或mFirstTouchTarget != null时需判断是否需要去拦截,其中mFirstTouchTarget在事件由ViewGroup的子元素处理成功时会被赋值,也就是说当ViewGroup不拦截事件并交由子元素处理时 mFirstTouchTarget != null 成立。
所以如果ViewGroup拦截了当前事件,当ACTION_MOVE和ACTION_UP事件到来时,(actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null )条件不成立,则不会再执行onInterceptTouchEvent(ev)方法,直接进入else,设置 intercepted = true,这个事件序列的其他事件都会由viewGroup处理;
接着里面还有一个判断是否拦截,其中有个标记位 FLAG_DISALLOW_INTERCEPT,这个标记位是通过requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法设置的,一般用于子view中; FLAG_DISALLOW_INTERCEPT 的值一旦设置后,ViewGroup 将无法拦截除ACTION_DOWN以外的事件,因为在ViewGroup的dispatchTouchEvent方法中,首先会判断ACTION_DOWN事件,然后初始化属性,其中在resetTouchState()方法中对 FLAG_DISALLOW_INTERCEPT 初始化,因此每次ACTION_DOWN事件时,ViewGroup总是会调用自己的 onInterceptTouchEvent(ev) 方法来询问是否需要拦截。
由此可以看出,当ViewGroup决定拦截事件后,那么后续的点击事件将会默认交由它处理并且不再调用它的onInterceptTouchEvent方法,也说明了onInterceptTouchEvent方法并不是每次都会调用。另外子View也可以通过requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法干预父View的事件分发过程。
继续往下,事件会往下分发交由子view处理:
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);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
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);
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;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
首先是从倒序遍历子view(即是从最上层的子view开始遍历),判断子view是否能够接收到点击事件,如果能子view能够接受到点击事件,则交由子view来处理;其中判断:
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
一个是判断子view是否在播放动画,一个是判断点击事件的坐标是否落在子元素的区域内,如果这两个条件都满足,那么事件就会交由它来处理。
接着看到 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)),跟进到
dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)方法内部:
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;
}
因为传递的child !=null 因此会调用 child 的dispatchTouchEvent方法,这样事件就交由子元素处理了;
回到上面的代码,看到这一行
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;其中
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
也即是说如果子元素的dispatchTouchEvent返回true,则会对mFirstTouchTarget 赋值,同时跳出for循环;如果返回false,ViewGroup就会把事件分发给下一个子元素。
继续往下看到
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
如果遍历所有子元素后事件都没有被合适的处理,在dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)方法中,如果传入的child为null,则会调用super.dispatchTouchEvent(event),由于ViewGroup也是View的子类,所以这里就转到了View的dispatchTouchEvent方法,即事件开始交由View来处理。
接着看到view的dispatchTouchEvent方法中,关键代码:
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;
}
}
首先会判断是否设置了onTouchListener监听,如果OntouchListener的onTouch方法返回true,那么后面的onTouchEvent方法将不会被调用;
在看到onTouchEvent方法的实现,其中关键代码:
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
...
}
mIgnoreNextUpEvent = false;
break;
...
}
return true;
}
可以看出只要View的((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 一个为true,则onTouchEvent返回true,也就消费了事件,在看到后面会触发performClick方法,具体实现如下:
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
可以看出,如果设置了OnClickListner,则onClick方法会被调用;
LONG_CLICKABLE默认为false,而CLICKABLE属性是否为false和具体的view有关,确切的说是可点击的view其CLICKABLE为true,不可点击的view其CLICKABLE为false;通过setClickale和setLongClickable可以改变view的CLICKABLE和LONG_CLICKABLE属性。