Android View事件分发源码分析
引言
上一篇文章我们介绍了View的事件分发机制,今天我们从源码的角度来学习下事件分发机制。
Activity对点击事件的分发过程
事件最先传递给当前Activity,由Activity的dispatchTouchEvent进行事件分发,具体的工作是有Activity内部的Window来完成的。Window会将事件传递给DecorView,DecorView一般就是当前界面的底层容器(即setContentView所设置的View的父容器)。下面我们来看一下Activity的dispatchTouchEvent方法的源码。源代码如下:
/**
* 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);
}
我们分析上面的源代码,事件首先交给Activity所属的Window进行分发,如果返回true,那么说明事件被子View拦截并且处理了。如果返回false说明事件没人处理,所有的View的onTouchEvent都返回false,那么这时候只有Activity的onTouchEvent会被调用了(还记得上一篇文章写的那些结论吗?看看第5条)。
那么Window是如何将事件传递给ViewGroup的呢?我们看源代码会知道,Window是一个抽象类,Window的superDispatchTouchEvent方法也是一个抽象方法,我们需要找到Window的实现类才行。Window的实现类是PhoneWindow类,我们来看PhoneWindow是如何处理点击事件的。代码如下:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
看到这里,逻辑变得很清晰了,PhoneWindow将事件直接传递给DecorView,那DecorView又是什么呢?在上一篇文章中,我们聊到过,DecorView是顶层的View。我们接着方法往下看,我们看到如下代码:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
DecorView事件分发也是要依靠父类方法的,DecorView继承自FrameLayout,而后者继承自ViewGroup。很显然DecorView的事件分发过程调用的是ViewGroup里面的方法。
ViewGroup对事件分发过程
上面的分析已经讲明,事件到达顶层View后会调用ViewGroup的dispatchTouchEvent方法进行分发。下面的逻辑要分两种情况来说:
第一种:如果ViewGroup的onInterceptTouchEvent方法返回true,表示ViewGroup需要拦截该事件,这个事件会由ViewGroup来进行处理。
第二种:如果ViewGroup的onInterceptTouchEvent方法返回false,表示ViewGroup不需要拦截该事件,这时候这个事件会传递给它所在的点击事件链上的子View,这时候子View的dispatchTouchEvent会被调用,这时候事件就有顶级View传递到了下一级的View。接下来的传递过程和上面的过程类似,如此往复,直到整个事件的分发。
下面我们来看下ViewGroup中事件分发代码的逻辑,先看第一段。
// 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;
}
从上面的代码我们知道,ViewGroup在如下两种情况下会判断是否要拦截当前事件:事件类型为ACTION_DOWN或者mFirstTouchTarget!=null。那么什么情况下mFirstTouchTarget!=null这个条件成立呢?通过后面的代码逻辑我们知道,当ViewGroup不拦截事件,并将事件交给子View处理时,mFirstTouchTarget!=null这个条件就是成立的。反过来说,一旦事件由ViewGroup拦截并且自己来处理时,mFirstTouchTarget!=null就是不成立的,那么当ACTION_MOVE和ACTION_UP事件到来时,由于if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)这个条件为false就导致ViewGroup的onInterceptTouchEvent方法不会被调用,并且同一事件序列中的其他事件都会默认交给他来处理。
这里还有一种特殊情况,就是FLAG_DISALLOW_INTERCEPT标记位,这个标记位是通过requestDisallowInterceptTouchEvent这个方法来设置的,一般用于子View中。FLAG_DISALLOW_INTERCEPT设置后,ViewGroup将无法拦截除ACTION_DOWN以外的其他点击事件。在进行事件分发时,如果是ACTION_DOWN事件,会重置这个标记位,这导致子View中设置的这个标记位无效,因此,当面对ACTION_DOWN事件时,ViewGroup总会调用自己的dispatchTouchEvent方法来询问自己是否要拦截事件。代码如下:
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
注意这段代码是在上面一个代码段之前的哦,去源码看就知道了。
下面我们来看ViewGroup不拦截事件的时候,事件会向下分发交给它子View进行处理,这段代码如下:
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
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 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的所有子元素,然后判断子元素时候能够接收到点击事件。能否接收到点击事件主要由两点来衡量:子元素是否在播放动画和点击事件的坐标是否落在子元素的区域内。如果某一个子元素满足这两个条件,那么事件就会传递给它。
我们看代码第44行,dispatchTransformedTouchEvent实际上调用的就是子元素的dispatchTouchEvent方法。后面会介绍child这个参数时候为null带来的影响。我们来看这段代码:
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
从上面的代码我们看出来,如果child为null那么就直接调用View的dispatchTouchEvent方法,进行事件的处理。如果child!=null就调用child.dispatchTouchEvent方法进行下一轮的事件分发。如果子元素的dispatchTouchEvent方法返回true,那么mFirstTouchTarget会被赋值,并且跳出for循环(第60行代码),代码如下:
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
如果子元素的dispatchTouchEvent返回false,ViewGroup会把事件分发给下一个子元素进行处理(结合前两段代码)。
其实mFirstTouchTarget真正的赋值过程是在addTouchTarget方法内部完成的,mFirstTouchTarget是一种单链表结构,其是否被赋值,将直接影响到ViewGroup对事件的拦截策略,如果mFirstTouchTarget为null,那么ViewGroup就默认拦截接下来同一序列中的所有点击事件,这一点在前面已经介绍过。
如果遍历ViewGroup后事件都没有被合适的处理,那么这包含两种情况,第一种是ViewGroup没有子元素;第二种是子元素处理了点击事件,但是在dispatchTouchEvent中返回false,这一般是onTouchEvent方法返回false,在这两种情况下,ViewGroup会自己处理点击事件。看下面代码:
// 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);
}
看到第三个参数传递的null了吗?上面我们分析过,会调用View的dispatchTouchEvent方法。这时候点击事件就交给View来处理了。
View对点击事件的处理
View对点击事件的处理稍微简单一些,注意这里的View不包括ViewGroup。我们来看它的dispatchTouchEvent方法源代码:
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
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)) {
//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(这里不包括ViewGroup)是一个单独的元素,它没有子元素因此无法向下传递事件,所以他只能自己处理事件。从上面的代码中,我们可以看出View对点击事件的处理过程,首先会判断有没有设置OnTouchListener。如果OnTouchListener中的onTouch方法返回true,那么onTouchEvent就不会被调用,可见OnTouchListener优先级是高于onTouchEvent的。
接下来我们来分析onTouchEvent的实现。我们分段来介绍,部分实现如下:
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处于不可用状态下时View照样会消耗点击事件。如果View设置有代理,那么还会执行TouchDelagate的onTouchEvent方法,这个onTouchEvent的工作机制应该和OnTouchListener类似。代码如下:
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
下面我们再来看一下onTouchEvent方法对点击事件的具体处理,代码如下:
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
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)) {
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; case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false; if (performButtonActionOnTouchDown(event)) {
break;
} // Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0);
}
break; case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break; 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;
}
我们从上面的代码中看到,只要View的CLICKABLE和LONG_CLICKABLE其中有一个true,就会消耗掉事件。即onTouchEvent方法true,不管是不是DISABLE状态。然后就是当ACTION_UP事件发生时,会触发performClick方法。如果View设置了OnClickListener,那么performClick方法内部会调用它的onClick方法。代码如下:
/**
* Call this view's OnClickListener, if it is defined. Performs all normal
* actions associated with clicking: reporting accessibility event, playing
* a sound, etc.
*
* @return True there was an assigned OnClickListener that was called, false
* otherwise is returned.
*/
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);
return result;
}
最后再说一句,调用setOnClickListener和setOnLongClickListener可以改变View的CLICKABLE和LONG_CLICKABLE属性。
最后再说一句,下一篇文章通过一个简单的例子来介绍滑动冲突。(*^__^*)
Android View事件分发源码分析的更多相关文章
- ViewGroup事件分发源码分析
1.AndroidStudio源码调试方式 AndroidStudio默认是支持一部分源码调试的,但是build.gradle(app) 中的sdk版本要保持一致, 最好是编译版本.运行版本以及手机的 ...
- android事件分发源码分析—笔记
昨天晚上从源码角度复习了一下android的事件分发机制,今天将笔记整理下放在网上.其实说复习,也是按着<android开发艺术探索>这本书作者的思路做的笔记. 目录 事件是如何从Acti ...
- view事件分发源码理解
有些困难无法逃避,没办法,那就只有去解决它.view事件分发对我而言是一块很难啃的骨头,看了<安卓开发艺术探索>关于这个知识点的讲解,看了好几遍,始终不懂,最终通过调试分析结果,看博客,再 ...
- Qt中事件分发源码剖析
Qt中事件分发源码剖析 Qt中事件传递顺序: 在一个应该程序中,会进入一个事件循环,接受系统产生的事件,而且进行分发,这些都是在exec中进行的. 以下举例说明: 1)首先看看以下一段演示样例代码: ...
- 深入理解Spring系列之十:DispatcherServlet请求分发源码分析
转载 https://mp.weixin.qq.com/s/-kEjAeQFBYIGb0zRpST4UQ DispatcherServlet是SpringMVC的核心分发器,它实现了请求分发,是处理请 ...
- Touch事件分发源码解析
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 以下源码基于Gingerbread 2.3.7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1.先看ViewGroup的di ...
- Android笔记--View绘制流程源码分析(二)
Android笔记--View绘制流程源码分析二 通过上一篇View绘制流程源码分析一可以知晓整个绘制流程之前,在activity启动过程中: Window的建立(activit.attach生成), ...
- Android笔记--View绘制流程源码分析(一)
Android笔记--View绘制流程源码分析 View绘制之前框架流程分析 View绘制的分析始终是离不开Activity及其内部的Window的.在Activity的源码启动流程中,一并包含 着A ...
- ApplicationEvent事件机制源码分析
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
随机推荐
- rman 中遇到 ORA-01861
RMAN> run{ 2> sql 'alter session set nls_date_format="yyyy-mm-dd hh24:mi:ss"'; 3> ...
- [Offer收割]编程练习赛15 A.偶像的条件[贪心]
#1514 : 偶像的条件 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi的学校正面临着废校的大危机.面对学校的危机,小Hi同学们决定从ABC三个班中各挑出一名同 ...
- matlab中画系统零极点的方法
写论文的时候由于需要画出系统的零极点图.但是之前不知道怎么用matlab画,今天研究了一下,拿出来和大家共享.所用到的matlab函数为zplane,matlab给出的解释如下: ZPLANE Z-p ...
- CentOS 安装PostregSQL9.2 同时出现pg安装错误
错误: Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /usr/local/bin ...
- Rails 添加新的运行环境
Rails自带了development.test和production三个environments 我们可以添加Staging database.yml staging: adapter: mysql ...
- Laya 图集动画
参考: 图集动画运用 一.准备素材 从爱给网找到几个素材 二.使用Laya的图集工具 菜单栏选择工具->图集打包工具,然后选择序列图所在的文件夹 生成了个.rec...说好的.atlas呢... ...
- CentOS上传下载查看命令
之前往CentOS中上传都用ftp软件,这里介绍一种另外的上传下载方式,两个命令轻松搞定.这两个命令目前只针对Xshell和SecureCRT等远程终端软件才支持,并且还会有时间的限制.大概30秒不上 ...
- AD初体验
首先是因为想用51做个小项目,所以想到不如成这个机会把AD学一下吧,老师说我们这个专业无论画图还是电路设计都得精通,想想自己还是能力欠缺,到大三了才开始学习绘制 原理图. 好了废话不说,下面说说我的第 ...
- POJ 1964&HDU 1505&HOJ 1644 City Game(最大0,1子矩阵和总结)
最大01子矩阵和,就是一个矩阵的元素不是0就是1,然后求最大的子矩阵,子矩阵里的元素都是相同的. 这个题目,三个oj有不同的要求,hoj的要求是5s,poj是3秒,hdu是1秒.不同的要求就对应不同的 ...
- POJ-1926 Pollution
Pollution Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 4049 Accepted: 1076 Description ...