編輯:關於Android編程
當觸摸一個View時,首先會調用View的dispatchTouchEvent(MotionEvent event)方法,關乎著事件的分發,所以首先看看這個方法
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; }看關鍵性的代碼,包含了四個判斷
li:是ListenerInfo,點進去可以看到是各種Listener,OnFocusChangeListener,OnScrollChangeListener,OnClickListener等等。
li.mOnTouchListener :很明顯是View的TouchListener,設置了setOnTouchListener()就不為空
(mViewFlags & ENABLED_MASK) == ENABLED:View是否是Enable的
li.mOnTouchListener.onTouch(this, event):onTouchListener的返回值,是否消耗了touch事件
也就是說這四個條件都滿足,dispatchTouchEvent方法就返回true,否則進入下面的判斷
接著看下一步
if (!result && onTouchEvent(event)) { result = true; }當上面的四個條件有一個不滿足時,就會執行onTouchEvent方法,onTouchEvent返回true結果就返回true。那麼下面就看看onTouchEvent(event)的源碼
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; }額,這段代碼有點長,看看下面幾點。
接著看下面的代碼,下面如果不是Disable的並且可點擊會進入switch的語句,在Up事件中會執行一個performClick()方法,點進入看
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; }
這裡可以看到mOnClickListener 不為空就會執行onClick方法,mOnClickListener 的賦值就是我們常用的setOnclickListener,並且返回true消耗掉了touch事件。也就是說onTouch事件要先於onClick事件,並且dispatchTouchEvent方法裡面的四個條件不能全部滿足才會執行(主要是onTouch不能返回true)onClick
看MotionEvent.ACTION_DOWN
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;這裡會檢測該view是否在一個滾動的容器裡面,如果在會有一個小的延遲再反饋的按下的狀態,以防的滾動
然後會去檢測是否是長按的事件
onTouchEvent()的返回結果
從源碼可以看出,只要View是Enable的並且滿足CLICKABLE、LONG_CLICKABLE、CONTEXT_CLICKABLE其中的一個條件都會返回true,消耗掉,否則返回false
下面用demo測試
自定義一個MyView繼承於View,重寫裡面的dispatchTouchEvent,onTouchEvent方法
1.在界面畫出該View,並且觸摸view,發現只打印下面
@Override public boolean dispatchTouchEvent(MotionEvent event) { Log.i(TAG, "dispatchTouchEvent"); return super.dispatchTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.i(TAG, "onTouchEvent ACTION_DOWN"); break; case MotionEvent.ACTION_MOVE: Log.i(TAG, "onTouchEvent ACTION_MOVE"); break; case MotionEvent.ACTION_UP: Log.i(TAG, "onTouchEvent ACTION_UP"); break; } return super.onTouchEvent(event); }
無論滑動還是離開都不會觸發其他事件。根據上面的源碼解釋mOnTouchListener為空(並沒有設置onTouchListener的監聽)所以會進入onTouchEvent方法,而該view又是disable的,所以onTouchEvent返回false,自然dispatchTouchEvent返回也是false。因為必須dispatchTouchEvent返回true才會接收到接下來的事件,所以才只接收到down的事件,不信我們把dispatchTouchEvent的返回值設置為true試試
2.dispatchTouchEvent的返回值設置為true
@Override public boolean dispatchTouchEvent(MotionEvent event) { Log.i(TAG, "dispatchTouchEvent"); super.dispatchTouchEvent(event); return true; // return super.dispatchTouchEvent(event); }
打印日志如下
可以看到有接收到後續的事件
3.設置onTouchListener
主界面設置view的touchListener監聽
view = (MyView) findViewById(R.id.view); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } });MyView
@Override public boolean dispatchTouchEvent(MotionEvent event) { Log.i(TAG, "dispatchTouchEvent"); return super.dispatchTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i(TAG, "onTouchEvent ACTION_DOWN"); break; case MotionEvent.ACTION_MOVE: Log.i(TAG, "onTouchEvent ACTION_MOVE"); break; case MotionEvent.ACTION_UP: Log.i(TAG, "onTouchEvent ACTION_UP"); break; } return super.onTouchEvent(event); }打印日志如下
發現並不會執行onTouchEvent,原理很簡單因為onTouch返回了true,使onTouchEvent不會執行,直接給dispatchTouchEvent返回了true,所以也可以接收到後續事件
如果把onTouch方法返回false,打印如下
返回false自然會執行onTouchEvent方法,由於是disable並且不可點擊,的所以給dispatchTouchEvent返回了false,自然不會有後續事件
還有很多其他的情況都可以根據源碼來分析出來執行結果。
本文實例講述了Android仿微信語音聊天功能代碼。分享給大家供大家參考。具體如下:項目效果如下:具體代碼如下:AudioManager.javapackage com.
為了使圖片浏覽器左右無限循環滑動 我們要自定義gallery的adapter如果要想自定義adapter首先要了解這幾個方法@Override public int ge
前言 Vitamio是我們團隊的誠意之作,除了要將VPlayer打造成Android最好的播放器,也要將Vitamio打造成Android最好的播放器組件。新版
在第二篇文章《Android中利用Handler實現消息的分發機制(一)》中,我們講到主線程的Looper是Android系統在啟動App的時候,已經幫我們創建好了,而如