android的事件分发主要在view和viewGroup中,那么android是怎么进行事件处理的通过源码来一探究竟。
首先所有事件都会调用dispatchTouchEvent方法。
View的事件分发
先看View的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent event) {
...
//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;
}
...
return result;
}
看到方法中会先去判断li.mOnTouchListener是否被设置过,并且调用li.mOnTouchListener的onTouch方法,如果没有设置过则调用onTouchEvent方法,那么可以发现li.mOnTouchListener的优先级高于onTouchEvent。
li.mOnTouchListener就是view.setOnTouchListener(new View.OnTouchListener())时进行的设置,这里不再详细展开。
接着来分析onTouchEvent方法,还是来看下源码:
public boolean onTouchEvent(MotionEvent event) {
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);
}
这里会先判断此时view的状态是否为disable,如果为disable则当前view也会消耗掉点击事件,但是不会触发点击事件回调。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
这里判断是否设置过mTouchDelegate并执行onTouchEvent,类似OnTouchListener,这里不深入讲解。
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
...
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
...
break;
这个一段代码可以看到只要view设置CLICKABLE或LONG_CLICKABLE中一个为true,都会消耗掉这个事件,最后返回true。
在MotionEvent.ACTION_UP状态时,会执行performClick,这个方法中会执行li.mOnClickListener.onClick方法,代码如下:
public boolean performClick() {
if (li != null && li.mOnClickListener != null) {
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
return result;
}
继续分析onTouchEvent方法:
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
checkForLongClick(0);
}
break;
在MotionEvent.ACTION_DOWN状态时,checkForLongClick会验证是否达到了长按的标准(DEFAULT_LONG_PRESS_TIMEOUT=500ms),当达到标准后如果设置了onLongClickListener会调用li.mOnLongClickListener.onLongClick方法。
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
在MotionEvent.ACTION_CANCEL状态时,会重置一些状态。
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
通过这一大段代码可以发现,是否消耗掉这个事件也就是是否返回true的关键点就是
(viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
这一大串的判断,那么这些状态是在什么时候设置的则是关键点。
view的LONG_CLICKABLE属性默认为false,CLICKABLE属性是否为false则与view的具体类型有关,向TextView默认为false,而Button为true。setClickable会设置view的CLICKABLE属性,setLongClickable和setContextClickable也同样会改变LONG_CLICKABLE和CONTEXT_CLICKABLE的属性。当setOnClickListener时会自动设置当前view的CLICKABLE属性为true,setOnLongClickListener和setOnContextClickListener也会分别设置LONG_CLICKABLE和CONTEXT_CLICKABLE为true。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
ViewGroup的事件分发
下边来看ViewGroup的dispatchTouchEvent方法。
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 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;
}
上边这段代码可以看到,当时间类型为MotionEvent.ACTION_DOWN或mFirstTouchTarget不为null时,才会有机会去执行onInterceptTouchEvent方法,MotionEvent.ACTION_DOWN事件很好理解,那mFirstTouchTarget这个变量通过后边的代码可以发现,当事件由ViewGroup的子元素处理时,mFirstTouchTarget会被赋值指向子元素,所以当ViewGroup不拦截并由子元素处理且不为MotionEvent.ACTION_DOWN时,onInterceptTouchEvent方法不会被调用。
可以看到经过上面的判断后,还会进行一次通过FLAG_DISALLOW_INTERCEPT的判断,那FLAG_DISALLOW_INTERCEPT这个标记位是怎么设置的呢?requestDisallowInterceptTouchEvent这个方法提供了修改这个标志位,一般会在子view中使用这个方法,这也为子view来控制父view提供了一种方式,当设置了这个标记位后ViewGroup将无法拦截除了MotionEvent.ACTION_DOWN以外的的其他事件,为什么MotionEvent.ACTION_DOWN会被排除?因为在状态为MotionEvent.ACTION_DOWN时ViewGroup会执行resetTouchState方法,这个方法会重置FLAG_DISALLOW_INTERCEPT标记位,所以在MotionEvent.ACTION_DOWN状态时一定会执行onInterceptTouchEvent方法。
经过上边代码后intercepted会获得一个值,这个值会影响到后续代码,继续向下看:
if (!canceled && !intercepted) {
...
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
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) {
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);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
当intercepted为false且不在ACTION_CANCEL状态时,会遍历这个ViewGroup的子View,当view符合可以接受点击事件和在子view的区域内时,会执行dispatchTransformedTouchEvent方法,这个方法用来让子元素执行dispatchTouchEvent方法,来具体看下这个方法内部实现:
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
handled = child.dispatchTouchEvent(transformedEvent);
}
通过上边代码看到当child!=null时会调用child的dispatchTouchEvent,这个child就是我们从dispatchTransformedTouchEvent方法传入的,前边一个章节介绍了view的dispatchTouchEvent,这里就会继续执行view的dispatchTouchEvent逻辑,这里不再赘述,可以再回看一遍上边关于view的讲解。
当子view返回true时,也就表明子view会消耗掉这个事件,那么会执行addTouchTarget方法给mFirstTouchTarget赋值并跳出当前遍历。
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
return handled;
}
当子view都返回了false也就是mFirstTouchTarget == null或者当前ViewGroup并没有子view时,最终会执行dispatchTransformedTouchEvent,上边我们已经分析了这个方法当child==null时会执行自身的super.dispatchTouchEvent,因为ViewGroup是View的一个子类,这时又回到了View的dispatchTouchEvent方法的逻辑之中。
上边的文章已经的详细的分析了view的事件分发过程,dispatchTouchEvent方法如果事件能够传递那么这个方法一定会调用,返回结果受当前的onTouchEvent和下级的dispatchTouchEvent共同作用,表示是否消耗当前的事件。onInterceptTouchEvent方法只会出现在ViewGroup的子类中,用来判断是否拦截当前事件,在某些情况下不会被调用。onTouchEvent用来处理点击事件,返回结果表示是否消耗掉当前事件。
总览事件分发过程
主要的分发逻辑分析完,还有一部分逻辑发生在Activity->Window->PhoneWindow->DecorView。通过一层层的传递传递到顶层View,顶层View一般来说是一个ViewGroup,就会进入我们文章分析的分发逻辑之中。当所有view的不响应这个事件时,最终Activity会执行onTouchEvent方法。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
至此已经完成了android的事件分发体系的讲解,看完后相信会对android 的事件分发有了进一步的理解,希望能够从文章中获得你所需要的知识。感谢观看。