【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 四 | View 事件传递机制 )
Android 事件分發(fā) 系列文章目錄
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( 驅(qū)動(dòng)層通過(guò)中斷傳遞事件 | WindowManagerService 向 View 層傳遞事件 )
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( Activity 中各層級(jí)的事件傳遞 | Activity -> PhoneWindow -> DecorView -> ViewGroup )
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 一 )
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 二 )
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 三 )
【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 四 | View 事件傳遞機(jī)制 )
文章目錄
- Android 事件分發(fā) 系列文章目錄
- 前言
- 一、View 的事件傳遞機(jī)制 ( dispatchTouchEvent )
- 二、觸摸事件 與 點(diǎn)擊事件 沖突處理
- 三、View 事件分發(fā)相關(guān)源碼
前言
接上一篇博客 【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 三 ) , 繼續(xù)分析 ViewGroup 的事件分發(fā)機(jī)制后續(xù)代碼 ;
一、View 的事件傳遞機(jī)制 ( dispatchTouchEvent )
在上一篇博客 【Android 事件分發(fā)】事件分發(fā)源碼分析 ( ViewGroup 事件傳遞機(jī)制 三 ) 二、當(dāng)前遍歷的子組件的事件分發(fā) 章節(jié) , 分析到 ViewGroup 的 dispatchTouchEvent 方法中的最終事件分發(fā) , 調(diào)用到了 View 的 dispatchTouchEvent 方法繼續(xù)向子組件分發(fā)觸摸事件 ;
View 組件設(shè)置 點(diǎn)擊監(jiān)聽器 View.OnClickListener , 觸摸監(jiān)聽器 View.OnTouchListener , 都設(shè)置在 View 的 View.ListenerInfo 類型成員中 ;
判斷該組件是否被用戶設(shè)置了 觸摸監(jiān)聽器 OnTouchListener , 如果設(shè)置了 , 則執(zhí)行被用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener ;
如果用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener 觸摸方法返回 true , 此時(shí)該分發(fā)方法的返回值就是 true ;
如果上述 li.mOnTouchListener.onTouch(this, event) 執(zhí)行的觸摸監(jiān)聽器觸摸方法返回值為 true , 則不會(huì)調(diào)用 View 組件自己的 onTouchEvent 方法了 , 在 onTouchEvent 方法中會(huì)調(diào)用 點(diǎn)擊監(jiān)聽器的方法 ;
如果用戶的 觸摸監(jiān)聽器 OnTouchListener 返回 true , 則 用戶的 點(diǎn)擊監(jiān)聽器 OnClickListener 會(huì)被屏蔽掉 ;
如果同時(shí)設(shè)置了 點(diǎn)擊監(jiān)聽器 OnClickListener 和 觸摸監(jiān)聽器 OnTouchListener , 此時(shí)需要做 觸摸事件 與 點(diǎn)擊事件的兼容處理 ;
View 的 onTouchEvent 方法分析 :
Click 點(diǎn)擊事件 , 是一次完整的按下 + 抬起操作 , 如果要判定點(diǎn)擊 , 需要同時(shí)有 MotionEvent.ACTION_DOWN + MotionEvent.ACTION_UP 事件 , 因此這里在 MotionEvent.ACTION_UP 事件分支中查找點(diǎn)擊事件 ;
最終找到了點(diǎn)擊事件的調(diào)用方法 performClickInternal 方法 ;
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {public boolean onTouchEvent(MotionEvent event) {if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {switch (action) {case MotionEvent.ACTION_UP:// 點(diǎn)擊事件 Click 是 按下 + 抬起 事件 // 如果要判定點(diǎn)擊 , 需要同時(shí)有 MotionEvent.ACTION_DOWN + MotionEvent.ACTION_UP 事件 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {// This is a tap, so remove the longpress checkremoveLongPressCallback();// Only perform take click actions if we were in the pressed stateif (!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) {// 此處創(chuàng)建點(diǎn)擊對(duì)象 mPerformClick = new PerformClick();}// 調(diào)用點(diǎn)擊事件 if (!post(mPerformClick)) {performClickInternal();}}}} }在 performClickInternal 方法中, 調(diào)用了 performClick 方法 ;
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {private boolean performClickInternal() {// Must notify autofill manager before performing the click actions to avoid scenarios where// the app has a click listener that changes the state of views the autofill service might// be interested on.notifyAutofillManagerOnClick();return performClick();} }在 performClick 方法中 , 調(diào)用了 li.mOnClickListener.onClick(this); , li.mOnClickListener 就是用戶設(shè)置的點(diǎn)擊事件監(jiān)聽器 ;
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {public boolean performClick() {// We still need to call this method to handle the cases where performClick() was called// externally, instead of through performClickInternal()notifyAutofillManagerOnClick();final boolean result;final ListenerInfo li = mListenerInfo;if (li != null && li.mOnClickListener != null) {playSoundEffect(SoundEffectConstants.CLICK);// 此處直接執(zhí)行了 點(diǎn)擊監(jiān)聽器 的點(diǎn)擊方法 li.mOnClickListener.onClick(this);result = true;} else {result = false;}sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);notifyEnterOrExitForAutoFillIfNeeded(true);return result;} }二、觸摸事件 與 點(diǎn)擊事件 沖突處理
通過(guò)分析上述 View 的 dispatchTouchEvent 方法的源碼可知 ,
如果觸摸事件 返回 true ,
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {public boolean dispatchTouchEvent(MotionEvent event) {//noinspection SimplifiableIfStatement// 設(shè)置的 觸摸監(jiān)聽器 就是封裝在該對(duì)象中 ListenerInfo li = mListenerInfo;// 判斷該組件是否被用戶設(shè)置了 觸摸監(jiān)聽器 OnTouchListenerif (li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED// 執(zhí)行被用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener&& li.mOnTouchListener.onTouch(this, event)) {// 如果用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener 觸摸方法返回 true// 此時(shí)該分發(fā)方法的返回值就是 true result = true;}} }則點(diǎn)擊事件就會(huì)被屏蔽 ;
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {public boolean dispatchTouchEvent(MotionEvent event) {// 如果上面為 true ( 觸摸監(jiān)聽器的觸摸事件處理返回 true ) , 就會(huì)阻斷該分支的命中 , 該分支不執(zhí)行了 // 也就不會(huì)調(diào)用 View 組件自己的 onTouchEvent 方法 // 因此 , 如果用戶的 觸摸監(jiān)聽器 OnTouchListener 返回 true // 則 用戶的 點(diǎn)擊監(jiān)聽器 OnClickListener 會(huì)被屏蔽掉 // 如果同時(shí)設(shè)置了 點(diǎn)擊監(jiān)聽器 OnClickListener 和 觸摸監(jiān)聽器 OnTouchListener // 觸摸監(jiān)聽器 OnTouchListener 返回 false , 點(diǎn)擊監(jiān)聽器 OnClickListener 才能被調(diào)用到 if (!result && onTouchEvent(event)) {result = true;}} }方法一 : 最簡(jiǎn)單的方法是 讓 觸摸事件 返回 false , 這樣 點(diǎn)擊和觸摸 事件 都可以共存 ;
方法二 : 如果一定要讓觸摸事件返回 true , 則只能在觸摸事件中 手動(dòng)調(diào)用 View 的 performClick() 方法 , 但是要注意 控制 觸摸的 按下 , 移動(dòng) , 抬起 事件 , 細(xì)粒度的分析與控制每個(gè)事件的關(guān)系 , 然后模擬出點(diǎn)擊事件的調(diào)用邏輯 ;
三、View 事件分發(fā)相關(guān)源碼
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource {/*** 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) {// 無(wú)障礙調(diào)用 , 輔助功能 // 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);}// 返回結(jié)果 boolean result = false;if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onTouchEvent(event, 0);}// 判定手指的動(dòng)作 final int actionMasked = event.getActionMasked();if (actionMasked == MotionEvent.ACTION_DOWN) {// Defensive cleanup for new gesturestopNestedScroll();}if (onFilterTouchEventForSecurity(event)) {if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {result = true;}//noinspection SimplifiableIfStatement// 設(shè)置的 觸摸監(jiān)聽器 就是封裝在該對(duì)象中 ListenerInfo li = mListenerInfo;// 判斷該組件是否被用戶設(shè)置了 觸摸監(jiān)聽器 OnTouchListenerif (li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED// 執(zhí)行被用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener&& li.mOnTouchListener.onTouch(this, event)) {// 如果用戶設(shè)置的 觸摸監(jiān)聽器 OnTouchListener 觸摸方法返回 true// 此時(shí)該分發(fā)方法的返回值就是 true result = true;}// 如果上面為 true ( 觸摸監(jiān)聽器的觸摸事件處理返回 true ) , 就會(huì)阻斷該分支的命中 , 該分支不執(zhí)行了 // 也就不會(huì)調(diào)用 View 組件自己的 onTouchEvent 方法 // 因此 , 如果用戶的 觸摸監(jiān)聽器 OnTouchListener 返回 true // 則 用戶的 點(diǎn)擊監(jiān)聽器 OnClickListener 會(huì)被屏蔽掉 // 如果同時(shí)設(shè)置了 點(diǎn)擊監(jiān)聽器 OnClickListener 和 觸摸監(jiān)聽器 OnTouchListener // 觸摸監(jiān)聽器 OnTouchListener 返回 false , 點(diǎn)擊監(jiān)聽器 OnClickListener 才能被調(diào)用到 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;}/*** 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();final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;if ((viewFlags & ENABLED_MASK) == DISABLED) {if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {setPressed(false);}mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;// A disabled view that is clickable still consumes the touch// events, it just doesn't respond to them.return clickable;}if (mTouchDelegate != null) {if (mTouchDelegate.onTouchEvent(event)) {return true;}}if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {switch (action) {case MotionEvent.ACTION_UP:// 點(diǎn)擊事件 Click 是 按下 + 抬起 事件 // 如果要判定點(diǎn)擊 , 需要同時(shí)有 MotionEvent.ACTION_DOWN + MotionEvent.ACTION_UP 事件 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;if ((viewFlags & TOOLTIP) == TOOLTIP) {handleTooltipUp();}if (!clickable) {removeTapCallback();removeLongPressCallback();mInContextButtonPress = false;mHasPerformedLongPress = false;mIgnoreNextUpEvent = false;break;}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 checkremoveLongPressCallback();// Only perform take click actions if we were in the pressed stateif (!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) {// 此處創(chuàng)建點(diǎn)擊對(duì)象 mPerformClick = new PerformClick();}// 調(diào)用點(diǎn)擊事件 if (!post(mPerformClick)) {performClickInternal();}}}if (mUnsetPressedState == null) {mUnsetPressedState = new UnsetPressedState();}if (prepressed) {postDelayed(mUnsetPressedState,ViewConfiguration.getPressedStateDuration());} else if (!post(mUnsetPressedState)) {// If the post failed, unpress right nowmUnsetPressedState.run();}removeTapCallback();}mIgnoreNextUpEvent = false;break;case MotionEvent.ACTION_DOWN:if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {mPrivateFlags3 |= PFLAG3_FINGER_DOWN;}mHasPerformedLongPress = false;if (!clickable) {checkForLongClick(0, x, y);break;}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 awaysetPressed(true, x, y);checkForLongClick(0, x, y);}break;case MotionEvent.ACTION_CANCEL:if (clickable) {setPressed(false);}removeTapCallback();removeLongPressCallback();mInContextButtonPress = false;mHasPerformedLongPress = false;mIgnoreNextUpEvent = false;mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;break;case MotionEvent.ACTION_MOVE:if (clickable) {drawableHotspotChanged(x, y);}// Be lenient about moving outside of buttonsif (!pointInView(x, y, mTouchSlop)) {// Outside button// Remove any future long press/tap checksremoveTapCallback();removeLongPressCallback();if ((mPrivateFlags & PFLAG_PRESSED) != 0) {setPressed(false);}mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;}break;}return true;}return false;}/*** Entry point for {@link #performClick()} - other methods on View should call it instead of* {@code performClick()} directly to make sure the autofill manager is notified when* necessary (as subclasses could extend {@code performClick()} without calling the parent's* method).*/private boolean performClickInternal() {// Must notify autofill manager before performing the click actions to avoid scenarios where// the app has a click listener that changes the state of views the autofill service might// be interested on.notifyAutofillManagerOnClick();return performClick();}/*** Call this view's OnClickListener, if it is defined. Performs all normal* actions associated with clicking: reporting accessibility event, playing* a sound, etc.** @return True there was an assigned OnClickListener that was called, false* otherwise is returned.*/// NOTE: other methods on View should not call this method directly, but performClickInternal()// instead, to guarantee that the autofill manager is notified when necessary (as subclasses// could extend this method without calling super.performClick()).public boolean performClick() {// We still need to call this method to handle the cases where performClick() was called// externally, instead of through performClickInternal()notifyAutofillManagerOnClick();final boolean result;final ListenerInfo li = mListenerInfo;if (li != null && li.mOnClickListener != null) {playSoundEffect(SoundEffectConstants.CLICK);// 此處直接執(zhí)行了 點(diǎn)擊監(jiān)聽器 的點(diǎn)擊方法 li.mOnClickListener.onClick(this);result = true;} else {result = false;}sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);notifyEnterOrExitForAutoFillIfNeeded(true);return result;}}
源碼路徑 : /frameworks/base/core/java/android/view/View.java
總結(jié)
以上是生活随笔為你收集整理的【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 四 | View 事件传递机制 )的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Android 事件分发】事件分发源码
- 下一篇: 【Android 事件分发】事件分发源码