Android事件分发机制笔记总结
一、View
首先先实现一个demo,新建一个自定义View,然后在Activity中实现一个点击事件和onTouch事件
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"onClick被调用了");
}
});
buttonView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//false 代表不消耗此事件
//true 代表消耗此事件
Log.i(TAG,"onTouch被调用了"+event.getAction());
return false;
}
});
调用return false的时候控制台打印结果如下
2507-2507/com.example.viewevent I/event: onTouch被调用了0
2507-2507/com.example.viewevent I/event: onTouch被调用了1
2507-2507/com.example.viewevent I/event: onClick被调用了
先后调用了onTouch两次和onClick一次,其中onTouch分别执行了手指按下、抬起两次操作,如果在按下同时移动,ACTION_MOVE也会执行
3215-3215/com.example.viewevent I/event: onTouch被调用了0
3215-3215/com.example.viewevent I/event: onTouch被调用了2
3215-3215/com.example.viewevent I/event: onTouch被调用了1
当onTouch方法return true的时候只会执行调用onTouch方法,其中按下,移动,抬起三次操作
在这里的onTouch return true和return false代表着消耗和不消耗此事件,也就是说消耗了该事件就代表者不会继续往下走了,这边从源码角度观察一下该流程是如何执行的。
1.dispatchTouchEvent 父容器 最先调用的方法,所以点击时最先找到的是继承自View下的方法
public boolean dispatchTouchEvent(MotionEvent event){
boolean result = false;//这里面定义了一个boolean
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
//这边的if条件中前三个基本恒定为true,
//关键为这个条件当li.mOnTouchListener.onTouch(this, event)返回true result被赋值为true
//这边的onTouch方法也就是我们Activity中实现的onTouch方法
}
//result为true,这边&&由于双目运算符的原因,不会去执行onTouchEvent方法
if (!result && onTouchEvent(event)) {
result = true;
}
}
//从Activity中setOnTouchListener进来
public void setOnTouchListener(OnTouchListener l) {
getListenerInfo().mOnTouchListener = l;
}
可以根据执行流程可以得知,由于没有执行onTouchEvent方法,表示的是该事件已被消耗,所以onClick在onTouchEvent中执行,修改onTouch方法中的return为false
public boolean onTouchEvent(MotionEvent event){
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
// 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();//关键方法,当手指抬起来去调用
}
break;
}
}
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);//Activity设置的onClick监听
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
//从Activity中setOnClickListener进来
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
小结:
onTouch
返回true消耗此事件:不会去执行onTouchEvent方法也就是不会去执行onClick方法
返回false不消耗此事件:执行onTouchEvent方法—-ACTION_UP中执行performClick()—-onClick()
二、ViewGroup
新建一个继承RelativeLayout的ViewGroup,并且实现三个方法
1.onTouchEvent:View中的方法,VeiwGroup也有,同View一样return true/false表示消耗/不消耗该事件
2.dispatchTouchEvent:是处理触摸事件分发,大多数情况是从Activity的dispatchTouchEvent开始的。执行super.dispathTouchEvent,事件向下分发
3.onInterceptTouchEvent:是ViewGroup里的方法,默认返回false不拦截,返回true表示拦截,ViewGroup作为一个容器,所以它必定可以容纳好多孩子(子View),所以拦截指的是判断事件要不要通知它的孩子。
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(TAG,"MyViewGroup onTouchEvent "+event.getAction());
return super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.i(TAG,"MyViewGroup onInterceptTouchEvent "+ev.getAction());
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i(TAG,"MyViewGroup dispatchTouchEvent "+ev.getAction());
return super.dispatchTouchEvent(ev);
}
将xml中的父容器替换为自定义的ViewGroup,并且实现Activity中的dispatchTouchEvent()和onTouchEvent()两个方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i(TAG,"MainActivity dispatchTouchEvent"+ev.getAction());
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(TAG,"MainActivity onTouchEvent"+event.getAction());
return super.onTouchEvent(event);
}
运行结果,调用顺序如下:
6371-6371/com.example.viewevent I/event: MainActivity dispatchTouchEvent0
6371-6371/com.example.viewevent I/event: MyViewGroup dispatchTouchEvent 0
6371-6371/com.example.viewevent I/event: MyViewGroup onInterceptTouchEvent 0
6371-6371/com.example.viewevent I/event: MyViewGroup onTouchEvent 0
6371-6371/com.example.viewevent I/event: MainActivity onTouchEvent0
6371-6371/com.example.viewevent I/event: MainActivity dispatchTouchEvent1
6371-6371/com.example.viewevent I/event: MainActivity onTouchEvent1
以上顺序为首先执行Activity中的dispathTouchEvent->ViewGroup中的三兄弟->Activity->onTouchEvent、dispatchTouchEvent、onTouchEvent
从Activity实现的方法dispatchTouchEvent起点寻找super.dispatchTouchEvent实现了是Activity的,如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {//这边又是交给window处理
return true;//当return true,就不会执行底下的onTouchEvent(ev)
}
return onTouchEvent(ev);
}
getWindow().superDispatchTouchEvent(ev)点进去发现是一个抽象方法,如下:
/**
* Used by custom windows, such as Dialog, to pass the touch screen event
* further down the view hierarchy. Application developers should
* not need to implement or call this.
*
*/
public abstract boolean superDispatchTouchEvent(MotionEvent event);
而实现了这个方法是它的子类PhoneWindow,如下:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
根据谷歌工程师友好的命名方式mDecor即可直接得知就是DecorView,而DecorView代表的是整个View的树形结构中最顶层的位置,它是一个FrameLayout布局,代表了整个应用的界面
//DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
//FrameLayout未实现,再往上走发现ViewGroup中实现了该方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev){
}
经过了这样的流程就来到了自定义的ViewGroup实现的方法当中
修改自定义ViewGroup中的dispatchTouchEvent方法中的返回值为true,运行结果如下:
7209-7209/com.example.viewevent I/event: MainActivity dispatchTouchEvent0
7209-7209/com.example.viewevent I/event: MyViewGroup dispatchTouchEvent 0
7209-7209/com.example.viewevent I/event: MainActivity dispatchTouchEvent1
7209-7209/com.example.viewevent I/event: MyViewGroup dispatchTouchEvent 1
1.Activity.dispatchTouchEvent
2.ViewGroup.dispatchTouchEvent
return true-> ViewGroup.onInterceptTouchEvent
return false-> Activity.onTouchEvent
3.ViewGroup.onTouchEvent
return true-> Activity.dispatchTouchEvent
return false-> Activity.onTouchEvent
ViewGroup中dispatchTouchEvent源码,分析onInterceptTouchEvent return true/false拦截的情况,如下
@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;
/*
* 第一步:对于ACTION_DOWN进行处理(Handle an initial down)
* 因为ACTION_DOWN是一系列事件的开端,当ACTION_DOWN进行一些初始化操作。
* 从源码注释也能够看出来,清除以往Touch状态(state)开始新的手势(gesture)
* cancelAndClearTouchTargets(ev)中有一个重要的操作:
* 将mFirstTouchTarget设置为null
* 随后再resetTouchState()中充值Touch状态标识
*/
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {//一个事件最开始的地方,按下
//取消和清除所有触摸目标。
cancelAndClearTouchTargets(ev);//1.
resetTouchState();//恢复触摸状态,标志位
}
/*
* 第二步:检查是否要拦截(Check for interception)
* 在dispatchTouchEvent(MotionEvent v)这段代码中
* 使用变量intercepted来标记ViewGroup是否拦截Touch事件的传递
* 该变量在后续代码中起着重要的作用
*
* 伪拦截 intercepted=true
*/
// Check for interception.是否拦截
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//2. requestDisallowInterceptTouchEvent(true);//不让父控件拦截
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {//设置不让父控件拦截true,disallowIntercept为true
intercepted = onInterceptTouchEvent(ev);//所以就不会去执行onInterceptTouchEvent
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;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
/*
* 第三步:检查cancel(Check for cancelation)
*/
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
/*
* 第四步:事件分发(Update list of touch targets for pointer up or cancel, if needed)
*/
//不是ACTION_CANCEL并且ViewGroup的拦截标志位intercepted为false(不拦截)
if (!canceled && !intercepted) {//intercepted伪拦截
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
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;
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 = buildTouchDispatchChildList();//重排序
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//事件分发 down 遍历子控件的过程
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
//preorderedList.get(childIndex)
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;
}
//View处在执行动画,可见性 不接受
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//执行到了下面
//child绝对会接受事件
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();
}
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;
}
}
}
//当onInterceptTouchEvent return true
//所以intercept = true 而mFirstTouchTarget=null成立
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
//这边第三个参数需要传入的是一个View,而这边传入为null
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);//3.
} 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;
}
//1
private void cancelAndClearTouchTargets(MotionEvent event) {
//如果第一次触发Down mFirstTouchTarget=null 第二次!=null
if (mFirstTouchTarget != null) {
boolean syntheticEvent = false;
if (event == null) {
final long now = SystemClock.uptimeMillis();
event = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
syntheticEvent = true;
}
//多手指触摸支持32个触摸点,这边TouchTarget是一个单项列表
for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
resetCancelNextUpFlag(target.child);
dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
}
clearTouchTargets();//非第一次,全部触摸事件置空初始化状态
if (syntheticEvent) {
event.recycle();
}
}
}
//2.不让父控件拦截
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
// We're already in this state, assume our ancestors are too
return;
}
if (disallowIntercept) {//true
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;//标志位设置为FLAG_DISALLOW_INTERCEPT
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
// Pass it up to our parent
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
//3.真正做事件分发的
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
//cancel=false
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;
}
// Perform any necessary transformations and dispatch.
//第一次按下去的时候 如果被拦截了child==null
if (child == null) {
//去执行View中的dispatchTouchEvent
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}