安卓中View的事件分发机制

阅读: 评论:0

安卓中View的事件分发机制

安卓中View的事件分发机制

前言

都到了二月份了,才是我2020年的第一篇文章,今天是正月十五元宵节。过了今天意味着春节正式结束了。然而大家都知道今年的春节是个非常难受痛苦的春节。新型冠状病毒席卷整个中国,在这里向奋斗在一线的医护人员致敬,您们辛苦了!! 同时也希望国家早日战胜病毒,武汉加油,中国加油!

事件从Activity传递到跟ViewGroup

1.当事件产生后,首先传递到当前的Activity,调用Activity的方法dispatchTouchEvent。
这里可以很清楚的看清Activity的onTouchEvent回调的时机即getWindow().superDispatchTouchEvent(ev) 返回false时触发

    public boolean dispatchTouchEvent(MotionEvent ev) {if (ev.getAction() == MotionEvent.ACTION_DOWN) {onUserInteraction();//空方法}//superDispatchTouchEvent(ev)是抽象方法,调用的是了PhoneWindowif (getWindow().superDispatchTouchEvent(ev)) {//1return true;}return onTouchEvent(ev);}

2.PhoneWindow里的方法,由上面的1处调用,又传给了mDecor,踢皮球

   @Overridepublic boolean superDispatchTouchEvent(MotionEvent event) {return mDecor.superDispatchTouchEvent(event);//2}

3.DecorView里的方法,由上面的2处调用,因为 DecorView 继承了FrameLayout,所以传到了ViewGroup的

 public boolean superDispatchTouchEvent(MotionEvent event) {return super.dispatchTouchEvent(event);}

ViewGroup相关的方法

1.ViewGroup的dispatchTouchEvent
如果当前View拦截了某个事件 那么在同一个事件序列中就不会再次被调用

   @Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {...boolean handled = false;if (onFilterTouchEventForSecurity(ev)) {final int action = ev.getAction();final int actionMasked = action & MotionEvent.ACTION_MASK;// 处理DOWN事件if (actionMasked == MotionEvent.ACTION_DOWN) {//开始新的触摸手势时,放弃所有先前的状态cancelAndClearTouchTargets(ev);//会把mFirstTouchTarget置为nullresetTouchState();}// 检查是否拦截final boolean intercepted;//当前ViewGroup没有拦截,交由子View处理if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null) {final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;//拦截了,执行onInterceptTouchEvent方法if (!disallowIntercept) {//触发onInterceptTouchEvent,默认falseintercepted = onInterceptTouchEvent(ev);ev.setAction(action); } else {//这里没有拦截intercepted = false;}} else {如果触发的是ACTION_MOVE 和ACTION_UP,直接走这里intercepted = true;}return handled;}

2.ViewGroup的onInterceptTouchEvent方法默认返回false

  public boolean onInterceptTouchEvent(MotionEvent ev) {if (ev.isFromSource(InputDevice.SOURCE_MOUSE)&& ev.getAction() == MotionEvent.ACTION_DOWN&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)&& X(), ev.getY())) {return true;}return false;}

再继续看ViewGroup的dispatchTouchEvent()方法里剩余的代码

 @Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {...final View[] children = mChildren;//遍历ViewGroup子元素for (int i = childrenCount - 1; i >= 0; i--) {final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);//判断可访问性焦点    if (childWithAccessibilityFocus != null) {if (childWithAccessibilityFocus != child) {continue;}childWithAccessibilityFocus = null;i = childrenCount - 1;}//判断是否能接受到点击事件,触摸点是否在子view的范围内或者子view是否在播放动画if (!child.canReceivePointerEvents()|| !isTransformedTouchPointInView(x, y, child, null)) {ev.setTargetAccessibilityFocus(false);continue;}newTouchTarget = getTouchTarget(child);if (newTouchTarget != null) {newTouchTarget.pointerIdBits |= idBitsToAssign;break;}resetCancelNextUpFlag(child);//dispatchTransformedTouchEvent方法下面会看一下具体做什么if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {mLastTouchDownTime = ev.getDownTime();if (preorderedList != null) {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;}ev.setTargetAccessibilityFocus(false);}...}

3.ViewGroup的dispatchTransformedTouchEvent

 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits) {final boolean handled;final int oldAction = Action();if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {event.setAction(MotionEvent.ACTION_CANCEL);//如果有子view,调用子view的dispatchTouchEvent(event)方法,下面讲//否则调用super.dispatchTouchEvent(event)if (child == null) {handled = super.dispatchTouchEvent(event);} else {handled = child.dispatchTouchEvent(event);}event.setAction(oldAction);return handled;}...}

view相关的方法

1.View的dispatchTouchEvent(event)
如果mOnTouchListener不为null并且onTouch返回true,则表示事件被消费就不会执行onTouchEvent(event)

这里值得注意的是,OnTouchListener中的onTouch()方法执行优先级高于onTouchEvent(event)的。

 public boolean dispatchTouchEvent(MotionEvent event) {...boolean result = false;if (onFilterTouchEventForSecurity(event)) {if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {result = true;}ListenerInfo li = mListenerInfo;//如果mOnTouchListener不为null并且onTouch返回true,则表示事件被消费if (li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED&& Touch(this, event)) {result = true;}if (!result && onTouchEvent(event)) {result = true;}}return result;}

2.View的onTouchEvent(event),view的CLICKABLE和LONG_CLICKABLE有一个true,onTouchEvent()就会返回true消耗这个事件。而这两个值可以通过View的setOnClickListener和setOnLongClickListener来设置,也可以通过View的setClickable和setLongClickable设置

public boolean onTouchEvent(MotionEvent event) {...final int action = Action();final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {switch (action) {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) {// 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) {removeLongPressCallback();if (!focusTaken) {if (mPerformClick == null) {mPerformClick = new PerformClick();}if (!post(mPerformClick)) {performClickInternal();//重点在这,该方法里直接调用performClick()}}}...return true;}return false;}

3.View的performClick方法,如果view设置了OnClickListener,onClick()就会执行,整个事件就会被消费。

public boolean performClick() {final boolean result;final ListenerInfo li = mListenerInfo;//如果view设置了OnClickListener,onClick()就会执行,整个事件就会被消费。if (li != null && li.mOnClickListener != null) {playSoundEffect(SoundEffectConstants.CLICK);Click(this);result = true;} else {result = false;}sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);notifyEnterOrExitForAutoFillIfNeeded(true);return result;}

到这里,源码中的事件分发基本算是分析完了。

总结

从前面的事件分发源码的分析,我们可以大体用下面代码表示整个流程

public boolean dispatchTouchEvent(MotionEvent ev){boolean result = false;if(onInterceptTouchEvent(ev)){result = onTouchEvent(ev);}else{result = child.dispatchTouchEvent(ev);}return result;
}

这里onInterceptTouchEvent方法和onTouchEvent方法都在dispatchTouchEvent中调用。
当事件产生后会由Activity的dispatchTouchEvent来处理,传递给了PhoneWindow,再传递给了DecorView,最后传递给了顶层ViewGroup。如果ViewGroup的dispatchTouchEvent中判断onInterceptTouchEvent是否拦截,如果拦截true,则执行他的onTouchEvent(ev)方法,如果不拦截(默认),交个他的子元素dispatchTouchEvent来处理,一直反复下去。直到view没有子view。就会调用View的dispatchTouchEvent方法,最终调用View的onTouchEvent方法。

总的来说传递过称分为自上而下和自下而上:
自上而下传递规则:拦截为true,不继续向下传递,自己消费,拦截为false,继续向下传递。
自下而上传递规则:onTouchEvent为true时,自己消耗并处理,如果为false,传递上去父view的onTouchEvent处理。

本文发布于:2024-02-01 07:13:33,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170674281334809.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:机制   事件   安卓中   View
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23