距离我上一次写博客已经是大半年的时间了,自己一毕业之后就在做一个很大的项目,一直都没有时间去学习,去沉淀,去积累,感觉这样子的状态是不行的,所以最近又重新开始学习起来。因为我负责的部分有挺多点击,长按,滑动的事件,所以这次就分析一下android里面View的事件分发机制。
一、为什么要有事件分发
android里面的View都是树形结构的,那么几个view就有重叠在一起的可能性,当我们点击的时候,可能会有好几个view做出响应,这时候就需要明确指定这个事件谁处理,这时候就产生是事件的分发。
二、View的事件分发机制
点击事件分发里面有三个很重要的方法:
public boolean dispatchTouchEvent(MotionEvent ev)
用于事件的分发public boolean onInterceptTouchEvent(MotionEvent ev)
这个方法是在上面的那个方法里面调用的,主要是用于判断是否对事件进行拦截,如果这个view拦截了某个事件,则后续的同一个事件序列都不会调用,注意,在View里面没有提供该方法public boolean onTouchEvent(MotionEvent event)
用来处理点击事件
2.1Activity的组成
当点击事件产生之后,首先是先会传递到当前的Activity,接着是怎样继续分发的呢?这我们就要分析Activity的构成了。在Activity的onCreate()方法里面通常是要setContentView(),我们来看看:
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
这个getWindow()究竟是什么的?
public Window getWindow() {
return mWindow;
}
原来这个getWindow()获取的是Window类的实例,但是Window类是一个抽象类,就必须要有它的实现类,接下来我们在Activity的attach()方法里面找到了它的实现类就是PhoneWindow:
mWindow = new PhoneWindow(this, window, activityConfigCallback);
接着我们就去看PhoneWindow的setContentView()方法
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
......
}
这里面主要看的就是installDecor()里面的这个方法:
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
//关键代码部分1
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
//关键代码部分2
mContentParent = generateLayout(mDecor);
}
...
}
这里面只截取了一部分关键的代码,关键代码第一部分有一个变量mDecor,这个mDecor原来就是DecorView,而且这个DecorView是FrameLayout的子类,所以Activity最顶层的View是一个FrameLayout,就是这个DecorView。
new DecorView(context, featureId, this, getAttributes());
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks
这时候我继续看回PhoneWindow的installDecor()里面的关键代码2的generateLayout(mDecor),它还把DecorView传了进去。
protected ViewGroup generateLayout(DecorView decor) {
//根据不同的模式加载不同的布局,不同的layoutResource
...
mDecor.startChanging();
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
return contentParent;
}
所以一张图总结一下Activity的组成
2.2Activity事件分发机制
前面也说过了,点击事件产生之后,首先会传递到Activity里面,首先我们看看Activity的dispatchTouchEvent()方法:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
从上面的代码里面可以分析出来,首先Activity会将事件分发给所依附的Window来进行分发,通过之前的分析可以得知,这个Window就是PhoneWindow,所以我们看PhoneWindow的superDispatchTouchEvent()方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
原来PhoneWindow是直接将事件分发给DecorView,就是顶层的View,顶层的View通常就是ViewGroup,下面就来看看
2.3 ViewGroup事件分发机制
首先也是先看dispatchTouchEvent()方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action);
} else {
intercepted = false;
}
} else {
intercepted = true;
}
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
....
return handled;
}
首先会判断是否DOWN事件,如果是的话,就会将一些状态进行清空,重置FLAG_DISALLOW_INTERCEPT标志位,把mFirstTouchTarget = null置空,因为一个完整的事件序列是由DOWN开始,UP结束的。而这个mFirstTouchTarget和FLAG_DISALLOW_INTERCEPT究竟是什么,下面会逐一解开它的面纱。
ViewGroup有两种情况需要判断是否进行拦截事件,就是事件是ACTION_DOWN或者是mFirstTouchTarget != null。第一个就很好理解,那么第二个的mFirstTouchTarget,在一开始的时候也进行了清空,其实这个是当ViewGroup的子元素处理了该事件,那么这个mFirstTouchTarget就会被赋值为这个子元素。假如ViewGroup拦截了当前事件,mFirstTouchTarget != null 就会为false,当此时触发的是DOWN事件,就会调用onInterceptTouchEvent();当如果此时触发的是MOVE或者UP事件,则不会调用onInterceptTouchEvent,直接是intercepted = true,就是说同一序列里面的其他事件都会交由ViewGroup来处理。
这里面还有一个FLAG_DISALLOW_INTERCEPT的标志位,这个通常是在子View中进行设置的,设置了这个之后,证明子View拦截了该事件,那么就会导致ViewGroup是不能拦截MOVE、UP之类的非DOWN事件。既然是子View已经拦截了该事件,那么MOVE之类的事件ViewGroup肯定就不会拦截了。那么为什么要除了DOWN事件?这很容易理解,一项开发任务,项目经理都还没有拿到有什么工作,又怎么分配给下面的程序员进行处理。只要触发的是DOWN,ViewGroup总是会调用onInterceptTouchEvent来询问自己是否要拦截该事件。
那么ViewGroup不拦截事件的时候,又是怎样分派给子View的?继续看dispatchTouchEvent里面剩余的一些代码:
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);
}
if (preorderedList != null) preorderedList.clear();
首先它会去遍历ViewGroup的子元素,判断该子View是否正在播放动画或者是触摸的区域是否在子View的区域范围之内。符合这两个条件的,就会去调用dispatchTransformedTouchEvent()方法。
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;
}
...
return handled;
}
如果子View是非空的话,则会调用子View的dispatchTouchEvent方法,若是为空的话,就会调用父类的dispatchTouchEvent。
如果子View的dispatchTouchEvent返回true的话,ViewGroup的dispatchTouchEvent方法里面,就会为一开始说的mFirstTouchTarget赋值了
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
如果遍历了所有的子元素,还是没有被处理掉,这通常是有两种情况,就是子元素为空,第二种就是子元素处理了dispatchToucheEvent(),但是返回了false。当出现这种情况的话,就会自己来处理,相当于项目经理分配给你的任务,你能力不够不能处理,那么就只好把任务给回项目经理,由他自己处理。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
同样也是调用回dispatchTransformedTouchEvent,但是因为第三个参数是为null,所以就相当于调用View的dispatchTouchEvent(),就是说这个点击事件交由View来处理。
2.3View的点击事件处理
因为View已经是一个单独的元素了,不能再分发给下面的了,所以这里只能自己处理了。
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;
}
}
...
return result;
}
这里首先会判断View是否设置了OnTouchListener,并且OnTouchListener里面的onTouch()返回了true,如果是的话就不会调用onTouchEvent()方法。这里面就是证实了OnToucheListener > onToucheEvent,OnTouchListener的优先级会高一些。
接下来我们看看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();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED)
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
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 pr
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual st
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
...
}
return true;
}
return false;
}
通过这里可以发现只要clickable是LONG_CLICKABLE或者是CLICKABLE的其中一个,那么onTouchEvent就相当于true消费了这个事件。这两个值就是相当于长按或者是短按,通过setClickable和setLongClickable设置,也可以通过setOnClickListener和setOnLongClickListener来自动设置。接着在UP事件里面就会调用performClick方法
public boolean performClick() {
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;
}
peformClick()这里同样是判断是否设置了OnClickListener,进而调用内部的onClick方法。
三、总结
套用别人总结的一段代码来总结:
public boolean dispatchTouchEvent(MotionEvent e){
boolean result = false;
if (onInterpertTouchEvent(e)){
result = onTouchEvent(e);
}else{
result = child.dispatchTouchEvent(e);
}
return result;
}
任何的点击事件首先都会先调用dispatchTouchEvent,根据onInterceptTouchEvent()判断是否进行拦截,若是拦截的话就会调用自身的onTouchEvent(),若自己不拦截的话就会传递给它的子元素的dispatchTouchEvent继续进行判断。若传递到最底层,还是没有被消费,该事件就会往回传递,从下往上传递。