初探View之事件分发机制

前言

配合Andorid开发艺术探索笔记食用更佳

View的事件分发分一下四部分,每个部分对事件分发的处理是不一样的,从肉眼可见的顺序编写
首先上个源码

emmm

Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}

首先是交给附属的Window分发,如果返回了true,整个点击事件循环就结束(分发下去),否则交给Activity的onTouchEvent处理。

Window

public abstract boolean superDispatchTouchEvent(MotionEvent event);

是一个抽象方法,真正的实现在PhoneWindow

1
2
3
4
5
6
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}

事件传给了DecoView,这个就是我们所说的顶级View(也叫ViewRoot),一般是一个ViewGroup

在onCreate中的setContestView就是这个顶级View的一个子View

DecoView(顶级View)

伪代码思想

1
2
3
4
5
6
7
8
9
10
11
12
13
funtion dispathTouchEvent(event):
if (mOnTouchListener) {
onTouch(event)
} else {
if (onInterceptTouchEvent()) {
onTouchEvent() - > {
if (mOnClickListener) { // 如果设置了点击监听
onClick()
}
} else {
superDispathTouchEvent() // 分发
}

源码,ViewGroup的拦截逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) { // 一旦子元素处理之后,ViewGroup的onInterceptTouchEvent不再处理
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;
}

特别注意的是FLAG_DISALLOW_INTERCEPT这个标记位一旦设置后,ViewGroup无法拦截处理action_down之外的点击事件,

在ViewGroup分发事件的时候action_down会重置这个标记位,所以ViewGroup总是会调用onInterceptTouchEvent来询问是否拦截事件

ViewGroup不拦截的时候,源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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;
}

大致逻辑如下:

遍历所有的子元素,判断子元素是否能够接收到点击事件,是否在动画化中和点击事件的坐标是否在子元素的区域内

dispatchTransformedTouchEvent实际上就是调用子元素的dispatchTouchEvent方法

上面的child传递的就不是null,所以事件就交给子元素处理了

1
2
3
4
5
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}

如果子元素的dispatchTouchEvent返回true,那么跳出遍历的for循环,mFirstTouchTarget也会被赋值,否则false会继续把事件分发给子元素

addTouchTarget就已经完成了对mFirstTouchTarget的复制,那么ViewGroup就默认拦截同一序列的所有事件

如果遍历的子元素事件没有被合适处理,有两种情况,没有子元素和子元素已经处理了事件,但是dispatchTouchEvent返回了false(子元素在onTouchEvent返回了false)

这就会让ViewGroup自己处理点击事件

1
2
3
4
5
6
7
8
9
// 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);

第三个child位null,那么通过前的源码就可以知道会调用super.dispatchTouchEvent(event),这里就会到View的dispathcTouchEvent,事件也就交给了View去完成。

View对点击事件的处理

源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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;
}
}
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无法去分发事件,到头了,只能自己去处理事件。

首先,判断是否设置了OnTouchListener,如果Listener的onTouch方法返回true,那么onTouchEvent就不会被调用

证明了Listener的优先级是高于onTouchEvent的,外界处理事件

onTouchEvent部分源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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不可用,照样也会消耗点击事件(源码都tm解释给你听了)

假如view有代理,还会执行TouchDelegate的onTouchEvent

1
2
3
4
5
6
7
8
9
10
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}

具体的点击处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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();
}
}
}

可以看出只要CLIKABLE和LONG_CLICKABLE有一个是true,他就会消耗事件,onTouchEvent返回true,不管Disable庄涛,然后就是action_up发生出发performClick,

设置Listener之后就会调用onClick方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
}

其中View的Long Click默认false,ClickAble是由View自己决定的,我们也可自行改变这两个的属性,

分发机制已经梳理得很清晰了。

尾巴

每次进步一点,积累就会成长不少。一开始我对View是拒绝的,很长很复杂,但是通过自己慢慢厘清源码,配合网上或者书上的一些详解就可以啃下这个骨头。

分享到: