Android事件分发底层原理
1.简介
1.1事件构成
在Android中,事件(TouchEvent)主要包括点按、长按、拖拽、滑动等,所有的事件都由如下三个部分组成
按下(ACTION_DOWN)
移动(ACTION_MOVE)
抬起(ACTION_UP)
一般来说,一次完整的Touch事件,应该是由一个Down、一个Up和若干个Move组成。
1.2View的分发事件
public boolean dispatchTouchEvent(MotionEvent ev)如果事件能够传递到当前的View,那么此方法一定会被调用。
public boolean onInterceptTouchEvent(MotionEvent ev)用来判断是否拦截某个事件
public boolean onTouchEvent(MotionEvent ev)用来处理点击事件
ViewGroup的相关事件有三个:onInterceptTouchEvent、dispatchTouchEvent、onTouchEvent。View的相关事件只有两个:dispatchTouchEvent、onTouchEvent。
1.3滑动冲突处理:
(1)外部拦截方法 (在父容器的 onInterceptTouchEvent 进行控制,是否分发到子元素),遵循Android规范
(2)内部拦截方法(在子元素通过控制父容器的 requestDisallowInterceptTouchEvent 进行控制)
2.流程
Android中事件传递按照从上到下再从下到上进行层级传递,事件处理从Activity开始到ViewGroup再到View,如果View没有消费事件会再次从View到ViewGroup再到Activity最后事件被抛出消费掉。流转的流程图如下:
dispatchTouchEvent和TouchEvnet return false的 时候,事件都会回传给父控件的onTouchEvent处理
onInterceptTouchEvent默认为false不进行事件拦截,OnDispatchTouchEvnet默认为true进行事件分发,onTouchEvent需要根据具体的View是否设置了listener及具体View的实现进行区分是否为true
Activity的dispatchTouchEvent不管返回true或false都会进行分发
如果事件在具体的View或者ViewGroup的onTouchEvent返回true,则表明事件被消费,事件传递机制就会结束
3.示例
具体可以根据流程图修改对应方法返回值进行日志验证。这里就不一一进行日志输出显示。
public class MyView extends Button {
private String TAG = "MyView";
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TAG += getTag();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "MyView dispatchTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "MyView dispatchTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "MyView dispatchTouchEvent--ACTION_UP");
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "MyView onTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "MyView onTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "MyView onTouchEvent--ACTION_UP");
break;
}
boolean touch = super.onTouchEvent(event);
Log.i(TAG, "MyView onTouchEvent--touch" + touch);
return touch;
}
}```
public class MyViewGroup extends RelativeLayout {
private String TAG = "MyViewGroup";
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
TAG+=getTag();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "MyViewGroup dispatchTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "MyViewGroup dispatchTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "MyViewGroup dispatchTouchEvent--ACTION_UP");
break;
}
return super.dispatchTouchEvent(ev) ;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "MyViewGroup onInterceptTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "MyViewGroup onInterceptTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "MyViewGroup onInterceptTouchEvent--ACTION_UP");
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "MyViewGroup onTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "MyViewGroup onTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "MyViewGroup onTouchEvent--ACTION_UP");
break;
}
boolean touch = super.onTouchEvent(event);
Log.i(TAG, "MyViewGroup onTouchEvent--touch" + touch);
return touch;
}
}```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jd.test.myapplication.MainActivity">
<com.jd.test.myapplication.view.MyViewGroup
android:id="@+id/mg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="mg1">
<com.jd.test.myapplication.view.MyView
android:id="@+id/v3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="btn3"
android:text="btn3" />
</com.jd.test.myapplication.view.MyViewGroup>
</RelativeLayout>```
public class ViewEventActivity extends Activity {
Button btn3;
MyViewGroup myViewGroup1;
private String TAG="ViewEventActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_event);
btn3= (Button) findViewById(R.id.v3);
myViewGroup1= (MyViewGroup) findViewById(R.id.mg1);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "DecorView dispatchTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "DecorView dispatchTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "DecorView dispatchTouchEvent--ACTION_UP");
break;
}
return super.dispatchTouchEvent(ev);
//return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "DecorView onTouchEvent--ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "DecorView onTouchEvent--ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "DecorView onTouchEvent--ACTION_UP");
break;
}
boolean touch=super.onTouchEvent(event);
Log.d(TAG, "DecorView touch boolean---"+touch);
return touch;
}```
4.源码解析
1.Activity的TouchEvent流程
首先看一下Activity的dispatchTouchEvnet源码,实际是调用了Window的 superDispatchTouchEvent();
Activity:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}```
Window是一个抽象类,他的实现类是PhoneWindow,而PhoneWidow的最底层视图是mDecorView,是一个FrameLayout。其实也就是ViewGroup。
PhoneWindow:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}```
DecorView的 superDispatchTouchEvent
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}```
如果Activity有实现 dispatchTouchEvent回调则调用改回调,若没有则调用super的 dispatchTouchEvent,继续往子View进行事件分发
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final Callback cb = getCallback();
return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
: super.dispatchTouchEvent(ev);
}```
2.DispatchTouchEvent
ViewGroup:
/**
* {@inheritDoc}
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
//对于辅助功能的事件处理
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 处理原始的DOWN事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
//这里主要是在新事件开始时处理完上一个事件
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
//检查事件拦截
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); //恢复事件防止其改变
} 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;
}
//如果事件被拦截了,则进行正常的事件分发
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 检查事件是否取消
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// 如果有必要的话,为DOWN事件检查所有的目标对象
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//如果事件未被取消并未被拦截
if (!canceled && !intercepted) {
//如果有辅助功能的参与,则直接将事件投递到对应的View,否则将事件分发给所有的子View
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(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
//如果TouchTarget为空并且子元素不为0
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
//由上至下去寻找一个可以接收改事件的子View
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;
}
//如果这个子元素无法接收Pointer Event或这个事件电压根本就没有在子元素的边界范围内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
//那么就跳出该次循环继续遍历
continue;
}
//找到Event该由那个子元素持有
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);
//投递事件执行触摸操作
//如果子元素还是一个ViewGroup,则递归调用重复此过程
//如果子元素还是一个View,那么则会调用View的dispatTouchEvent,
//并最终由onTouchEvent处理
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// 子View在其边界范围内接收事件
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;
}
}
}
// 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);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
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;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
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 (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}```
View:
/**
- Dispatches a key shortcut event.
- @param event The key event to be dispatched.
- @return True if the event was handled by the view, false otherwise.
/
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return onKeyShortcut(event.getKeyCode(), event);
}
/* - 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;
}```
3.onInterceptTouchEvent
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}```
**4.TouchEvent**
/**
- Implement this method to handle touch screen motion events.
- <p>
- If this method is used to detect click actions, it is recommended that
- the actions be performed by implementing and calling
- {@link #performClick()}. This will ensure consistent system behavior,
- including:
- <ul>
- <li>obeying click sound preferences
- <li>dispatching OnClickListener calls
- <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
- accessibility features are enabled
- </ul>
- @param event The motion event.
- @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
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);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
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;
}
return false;
}```