一.概述
事情分发有多种类型, 本文首要介绍Touch相关的事情分发.
- 整个事情分发流程中,会有大量MotionEvent目标,该目标用于记载一切与移动相关的事情,比如手指接触屏幕事情。
- 一次完整的MotionEvent事情,是从用户接触屏幕到脱离屏幕。整个进程的动作序列:ACTION_DOWN(1次) -> ACTION_MOVE(N次) -> ACTION_UP(1次),
- 多点接触,每一个接触点Pointer会有一个id和index。关于多指操作,经过pointerindex来获取指定Pointer的触屏方位。比如,关于单点操作时获取x坐标经过getX(),而多点操作获取x坐标经过getX(pointerindex)
1.1 中心类对比
View,ViewGroup,Activity都能处理Touch事情, 它们之间处理的先后顺序和办法有所不同.
办法 | View | ViewGroup | Activity |
---|---|---|---|
dispatchTouchEvent | √ | √ | √ |
onInterceptTouchEvent | √ | ||
onTouchEvent | √ | √ | √ |
以上3个办法功用如下:
- dispatchTouchEvent(MotionEvent event), 事情分发
- onInterceptTouchEvent(MotionEvent ev), 事情阻拦,该办法只需ViewGroup所拥有
- onTouchEvent(MotionEvent event), 事情响应
1)View是一切视图目标的父类,完成了动画相关的接口Drawable.Callback, 按键相关的接口KeyEvent.Callback, 交互相关的接口AccessibilityEventSource。比如Button承继自View。
2)ViewGroup,是一个抽象类,一组View的集合,能够包含View和ViewGroup,是一切布局的父类或间接父类。承继了View,完成了ViewParent(用于与父视图交互的接口), ViewManager(用于增加、删去、更新子视图到Activity的接口)。比如常用的LinearLayout,RelativeLayout都是承继自ViewGroup。
3)Activity是Android四大基本组件之一,当手指接触到屏幕时,屏幕硬件一行行不断地扫描每个像素点,获取到接触事情后,从底层产生中断上报。再经过native层调用Java层InputEventReceiver中的dispatchInputEvent办法。经过层层调用,交由Activity的dispatchTouchEvent办法来处理。
二. 分发原理
当UI主线程收到底层上报的input事情,便会调用InputEventReceiver.dispachInputEvent办法.
接下来,便从图中的dispatchTouchEvent办法开端说起。
2.1 DecorView.dispatchTouchEvent
[-> PhoneWindow.java ::DecorView]
publicbooleandispatchTouchEvent(MotionEvent ev){
final Callback cb = getCallback();
// [见末节2.2]
return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
: super.dispatchTouchEvent(ev);
}
此处cb是指Window的内部接口Callback. 关于Activity完成了Window.Callback接口. 故接下来调用Activity类.
2.2 Activity.dispatchTouchEvent
[-> Activity.java]
publicbooleandispatchTouchEvent(MotionEvent ev){
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//第一次按下操作时,用户期望能与设备进行交互,可经过完成该办法
onUserInteraction();
}
//获取当时Activity的顶层窗口是PhoneWindow [见末节2.3]
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//当没有任何view处理时,交由activity的onTouchEvent处理
return onTouchEvent(ev); // [见末节2.2.1]
}
假如重写Activity的dispatchTouchEvent()办法,则会在分发事情前可处理接触事情的相关逻辑. 另外此处getWindow()回来的是Activity的mWindow成员变量,该变量赋值进程是在Activity.attach()办法, 可知其类型为PhoneWindow.
2.2.1 Activity.onTouchEvent
[-> Activity.java]
public boolean onTouchEvent(MotionEvent event) {
//当窗口需要关闭时,消费掉当时event
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
2.3 superDispatchTouchEvent
[-> PhoneWindow.java]
public boolean superDispatchTouchEvent(KeyEvent event) {
return mDecor.superDispatcTouchEvent(event); // [见末节2.4]
}
PhoneWindow的最顶View是DecorView,再交由DecorView处理。而DecorView的父类的父类是ViewGroup,接着调用 ViewGroup.dispatchTouchEvent()办法。为了精简篇幅,有些中心函数调用不涉及要害逻辑,可能会直接越过。
2.4 ViewGroup.dispatchTouchEvent
publicbooleandispatchTouchEvent(MotionEvent ev){
...
boolean handled = false;
//依据隐私战略而来决议是否过滤本次接触事情,
if (onFilterTouchEventForSecurity(ev)) { // [见末节2.4.1]
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 产生ACTION_DOWN事情, 则撤销并铲除之前一切的接触targets
cancelAndClearTouchTargets(ev);
resetTouchState(); // 重置接触状况
}
// 产生ACTION_DOWN事情或许现已产生过ACTION_DOWN;才进入此区域,首要功用是阻拦器
//只需产生过ACTION_DOWN事情,则mFirstTouchTarget != null;
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//可经过调用requestDisallowInterceptTouchEvent,不让父View阻拦事情
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//判别是否答应调用阻拦器
if (!disallowIntercept) {
//调用阻拦办法
intercepted = onInterceptTouchEvent(ev); // [见末节2.4.2]
ev.setAction(action);
} else {
intercepted = false;
}
} else {
// 当没有接触targets,且不是down事情时,开端持续阻拦接触。
intercepted = true;
}
...
//不撤销事情,同时不阻拦事情, 并且是Down事情才进入该区域
if (!canceled && !intercepted) {
//把事情分发给一切的子视图,寻找能够获取焦点的视图。
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // down事情等于0
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
removePointersFromTouchTargets(idBitsToAssign); //清空早先的接触目标
final int childrenCount = mChildrenCount;
//第一次down事情,同时子视图不会空时
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// 从视图最上层到基层,获取一切能接收该事情的子视图
final ArrayList<View> preorderedList = buildOrderedChildList(); // [见末节2.4.3]
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
/* 从最底层的父视图开端遍历, ** 找寻newTouchTarget,并赋予view与 pointerIdBits; ** 假如现已存在找寻newTouchTarget,说明正在接收接触事情,则跳出循环。 */
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;
}
//假如view不可见,或许接触的坐标点不在view的范围内,则越过本次循环
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
// 现已开端接收接触事情,并退出整个循环。
if (newTouchTarget != null) {
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
//重置撤销或抬起标志位
//假如接触方位在child的区域内,则把事情分发给子View或ViewGroup
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // [见末节2.4.4]
// 获取TouchDown的时间点
mLastTouchDownTime = ev.getDownTime();
// 获取TouchDown的Index
if (preorderedList != null) {
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
//获取TouchDown的x,y坐标
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//增加TouchTarget,则mFirstTouchTarget != null。 [见末节2.4.5]
newTouchTarget = addTouchTarget(child, idBitsToAssign);
//表明以及分发给NewTouchTarget
alreadyDispatchedToNewTouchTarget = true;
break;
}
ev.setTargetAccessibilityFocus(false);
}
// 铲除视图列表
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
//将mFirstTouchTarget的链表最后的touchTarget赋给newTouchTarget
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// mFirstTouchTarget赋值是在经过addTouchTarget办法获取的;
// 只需处理ACTION_DOWN事情,才会进入addTouchTarget办法。
// 这也正是当View没有消费ACTION_DOWN事情,则不会接收其他MOVE,UP等事情的原因
if (mFirstTouchTarget == null) {
//没有接触target,则由当时ViewGroup来处理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
//假如View消费ACTION_DOWN事情,那么MOVE,UP等事情相继开端履行
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
//当产生抬起或撤销事情,更新接触targets
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
} //此处大括号,是if (onFilterTouchEventForSecurity(ev))的结束
//通知verifier因为当时时间未处理,那么该事情其余的都将被疏忽
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
2.4.1 onFilterTouchEventForSecurity
public boolean onFilterTouchEventForSecurity(MotionEvent event) {
if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
&& (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
//隐私包含,则丢掉该事情
return false;
}
return true;
}
依据隐私战略来过滤接触事情。当回来true,表明持续分发事情;当回来flase,表明该事情应该被过滤掉,不再进行任何分发。
2.4.2 onInterceptTouchEvent
publicbooleanonInterceptTouchEvent(MotionEvent ev){
return false;
}
- 当回来true,表明该事情被当时视图阻拦;
- 当回来false,持续履行事情分发。
2.4.3 buildOrderedChildList
ArrayList<View>buildOrderedChildList(){
final int count = mChildrenCount;
if (count <= 1 || !hasChildWithZ()) return null;
if (mPreSortedChildren == null) {
mPreSortedChildren = new ArrayList<View>(count);
} else {
mPreSortedChildren.ensureCapacity(count);
}
final boolean useCustomOrder = isChildrenDrawingOrderEnabled();
for (int i = 0; i < mChildrenCount; i++) {
// 增加下一个子视图到列表
int childIndex = useCustomOrder ? getChildDrawingOrder(mChildrenCount, i) : i;
View nextChild = mChildren[childIndex];
float currentZ = nextChild.getZ(); //获取Z轴
int insertIndex = i;
//按Z轴,从小到大排序一切的子视图
while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
insertIndex--;
}
mPreSortedChildren.add(insertIndex, nextChild);
}
return mPreSortedChildren;
}
获取一个视图组的先序列表,经过虚拟的Z轴来排序。
publicfloatgetZ(){
return getElevation() + getTranslationZ();
}
getZ()
用于获取Z轴坐标。屏幕只需x,y坐标,而Z是虚拟的,可经过setElevation()
,setTranslationZ()
或许setZ()
办法来修改Z轴的坐标值。
2.4.4 dispatchTransformedTouchEvent
privatebooleandispatchTransformedTouchEvent(MotionEvent event,booleancancel, View child,intdesiredPointerIdBits){
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 int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
//因为某些原因,产生不一致的操作,那么将扔掉该事情
if (newPointerIdBits == 0) {
return false;
}
//分发的首要区域
final MotionEvent transformedEvent;
//判别预期的pointer id与事情的pointer id是否相等
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
//不存在子视图时,ViewGroup调用View.dispatchTouchEvent分发事情,再调用ViewGroup.onTouchEvent来处理事情
handled = super.dispatchTouchEvent(event); // [见末节2.4]
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
//将接触事情分发给子ViewGroup或View;
//假如是ViewGroup,则调用代码(2.1);
//假如是View,则调用代码(3.1);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY); //调整该事情的方位
}
return handled;
}
transformedEvent = MotionEvent.obtain(event); //复制该事情,来创建一个新的MotionEvent
} else {
//别离事情,获取包含newPointerIdBits的MotionEvent
transformedEvent = event.split(newPointerIdBits);
}
if (child == null) {
//不存在子视图时,ViewGroup调用View.dispatchTouchEvent分发事情,再调用ViewGroup.onTouchEvent来处理事情
handled = super.dispatchTouchEvent(transformedEvent); // [见末节2.4]
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
//将该视图的矩阵进行转换
transformedEvent.transform(child.getInverseMatrix());
}
//将接触事情分发给子ViewGroup或View;
//假如是ViewGroup,则 [见末节2.4]; 假如是View,则[见末节2.5];
handled = child.dispatchTouchEvent(transformedEvent);
}
//收回transformedEvent
transformedEvent.recycle();
return handled;
}
该办法是ViewGroup真实处理事情的当地,分发子View来处理事情,过滤掉不相干的pointer ids。当子视图为null时,MotionEvent将会发送给该ViewGroup。终究调用View.dispatchTouchEvent办法来分发事情。
2.4.5 addTouchTarget
privateTouchTargetaddTouchTarget(View child,intpointerIdBits){
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
调用该办法,获取了TouchTarget,同时mFirstTouchTarget不再为null。
2.5 View.dispatchTouchEvent
[-> View.java]
public boolean dispatchTouchEvent(MotionEvent event) {
...
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
//在Down事情之前,假如存在翻滚操作则中止。不存在则不进行操作
stopNestedScroll();
}
// mOnTouchListener.onTouch优先于onTouchEvent。
if (onFilterTouchEventForSecurity(event)) {
//当存在OnTouchListener,且视图状况为ENABLED时,调用onTouch()办法
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true; //假如现已消费事情,则回来True
}
//假如OnTouch()没有消费Touch事情则调用OnTouchEvent()
if (!result && onTouchEvent(event)) { // [见末节2.5.1]
result = true; //假如现已消费事情,则回来True
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// 处理撤销或抬起操作
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
- 先由OnTouchListener的OnTouch()来处理事情,当回来True,则消费该事情,不然进入2。
- onTouchEvent处理事情,的那个回来True时,消费该事情。不然不会处理
2.5.1 View.onTouchEvent
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
// 当View状况为DISABLED,假如可点击或可长按,则回来True,即消费事情
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
//当View状况为ENABLED,假如可点击或可长按,则回来True,即消费事情;
//与前面的的结合,可得出结论:只需view是可点击或可长按,则消费该事情.
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
setPressed(true, x, y);
}
if (!mHasPerformedLongPress) {
//这是Tap操作,移除长按回调办法
removeLongPressCallback();
if (!focusTaken) {
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
//调用View.OnClickListener
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
mUnsetPressedState.run();
}
removeTapCallback();
}
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
//获取是否处于可翻滚的视图内
boolean isInScrollingContainer = isInScrollingContainer();
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
//当处于可翻滚视图内,则延迟TAP_TIMEOUT,再反馈按压状况,用来判别用户是否想要翻滚。默认延时为100ms
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
//当不再翻滚视图内,则马上反馈按压状况
setPressed(true, x, y);
checkForLongClick(0); //检测是否是长按
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
if (!pointInView(x, y, mTouchSlop)) {
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
三. 总结
事情分发,从流程图:
-
onInterceptTouchEvent
回来值true表明事情阻拦,onTouch/onTouchEvent
回来值true表明事情消费。 - 接触事情先交由
Activity.dispatchTouchEvent
。再一层层往下分发,当中心的ViewGroup都不阻拦时,进入最底层的View后,开端由最底层的OnTouchEvent
来处理,假如一向不消费,则最后回来到Activity.OnTouchEvent
。 - ViewGroup才有
onInterceptTouchEvent
阻拦办法。在分发进程中,中心任何一层ViewGroup都能够直接阻拦,则不再往下分发,而是交由产生阻拦操作的ViewGroup的OnTouchEvent
来处理。 - 子View可调用
requestDisallowInterceptTouchEvent
办法,来设置disallowIntercept=true
,然后阻挠父ViewGroup的onInterceptTouchEvent
阻拦操作。 - OnTouchEvent由下往上冒泡时,当中心任何一层的OnTouchEvent消费该事情,则不再往上传递,表明事情已处理。
- 假如View没有消费ACTION_DOWN事情,则之后的ACTION_MOVE等事情都不会再接收。
- 只需
View.onTouchEvent
是可点击或可长按,则消费该事情. -
onTouch
优先于onTouchEvent
履行,上面流程图中省略,onTouch
的方位在onTouchEvent
前面。当onTouch
回来true,则不履行onTouchEvent
,不然会履行onTouchEvent。onTouch
只需View设置了OnTouchListener
,且是enable的才履行该办法。
这节首要从体系代码下手去看底层touch事情分发流程,内容冗杂,学习起来比较费时,也期望对你有所帮助,谢谢我们。