本文主要是介绍setOnTouchListener onTouchEvent setOnLongClickListener setOnClickListener 执行顺序及源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.先说 setOnClickListener setOnTouchListener onTouchEvent
1. 1先看运行结果 :
MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN
MyViewGroup-->onInterceptTouchEvent-->ACTION_DOWN
MyButton-->dispatchTouchEvent-->ACTION_DOWN
MyButton-->setOnTouchListener-->ACTION_DOWN
MyButton-->onTouchEvent-->ACTION_DOWN
MyViewGroup-->dispatchTouchEvent-->ACTION_UP
MyViewGroup-->onInterceptTouchEvent-->ACTION_UP
MyButton-->dispatchTouchEvent-->ACTION_UP
setOnTouchListener-->ACTION_UP
MyButton-->onTouchEvent-->ACTION_UP
MyButton-->setOnClickListener
1.2 源码分析
1.先看setOnLongClickListener方法
public void setOnLongClickListener(@Nullable OnLongClickListener l) {if (!isLongClickable()) {setLongClickable(true);}getListenerInfo().mOnLongClickListener = l;
}
public interface OnLongClickListener {boolean onLongClick(View v);
}
看到我们实例化的接口赋值给了mOnLongClickListener ,好这就够了,如果好奇getListenerInfo(),自己可以去了解下。
2.再看 setOnClickListener
public void setOnClickListener(@Nullable OnClickListener l) {if (!isClickable()) {setClickable(true);}getListenerInfo().mOnClickListener = l;
}
其实和setOnLongClickListener差不多 知道mOnClickListener 就行了。
3. setOnTouchListener
public void setOnTouchListener(OnTouchListener l) {getListenerInfo().mOnTouchListener = l;
}
public interface OnTouchListener {boolean onTouch(View v, MotionEvent event);
}
注意onTouch 是有返回值的,这点很重要。
4.再来看下 先从 MyButton-->dispatchTouchEvent 开始分析
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 gesturestopNestedScroll();}if (onFilterTouchEventForSecurity(event)) {if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {result = true;}//noinspection SimplifiableIfStatement// 这里是重点,当我们执行mOnTouchListener.onTouch 监听的 setOnTouchListener 的onTouch 返回值为true 时 result 赋值为true ,这里先执行了setOnTouchListener 方法ListenerInfo li = mListenerInfo;if (li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED&& li.mOnTouchListener.onTouch(this, event)) {result = true;}//当 result 为true是 onTouchEvent 就不会执行了,这就是我上边说的,返回值很重要,监听的setOnTouchListener 消耗掉了本次事件,onTouchEvent不会执行,那么setOnClickListener呢,当然就不会执行了,我们分析下onTouchEvent(event)就知道了。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;
}
5.onTouchEvent(event) 与 setOnClickListener 执行关系
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 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) {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 nowmUnsetPressedState.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 awaysetPressed(true, x, y);checkForLongClick(0, x, y);}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 buttonsif (!pointInView(x, y, mTouchSlop)) {// Outside buttonremoveTapCallback();if ((mPrivateFlags & PFLAG_PRESSED) != 0) {// Remove any future long press/tap checksremoveLongPressCallback();setPressed(false);}}break;}return true;}return false;
}
接着看
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 方法,现在我们应该知道这几个之间的关系了吧。
总结:最先执行setOnTouchListener 然后执行onTouchEvet 紧接着在onTouchEvet中执行了setOnClickListener ,当然如果setOnTouchtListener 返回了true 那么后边两部就都不会执行了。
2. setOnLongClickListener setOnTouchListener onTouchEvent
2.1执行顺序 结果
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->onInterceptTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->dispatchTouchEvent-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivity-->setOnTouchListener-->ACTION_DOWN
11-16 15:03:15.699 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->onTouchEvent-->ACTION_DOWN
11-16 15:03:16.200 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivityonLongClick: setOnLongClickListener
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->dispatchTouchEvent-->ACTION_UP
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyViewGroup-->onInterceptTouchEvent-->ACTION_UP
11-16 15:03:16.996 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->dispatchTouchEvent-->ACTION_UP
11-16 15:03:16.997 20721-20721/com.example.macbook.demoproject2 I/System.out: MainActivity-->setOnTouchListener-->ACTION_UP
11-16 15:03:16.997 20721-20721/com.example.macbook.demoproject2 I/System.out: ------>MyButton-->onTouchEvent-->ACTION_UP
这次我把详细的log粘出来了,先看两个节点时间
1. MyViewGroup-->dispatchTouchEvent-->ACTION_DOWN 到 setOnLongClickListener
11-16 15:03:15.699 -----------------》 11-16 15:03:16.200 从按下到触发长按事件的时间
2.setOnLongClickListener 到 MyViewGroup-->dispatchTouchEvent-->ACTION_UP
11-16 15:03:16.200 ----------------------》11-16 15:03:16.996 这个是触发长按事件到我手指抬起触发父类的第一个方法时间
2.2 源码分析
在分析之前先有几个问题
1.长按事件到底啥时执行,按下后多久执行。
2.触发后为啥我的点击事件没有了。
从MyButton-->onTouchEvent ACTION_DOWN 开始分析
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 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) {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 nowmUnsetPressedState.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 awaysetPressed(true, x, y);//这里就是长按事件checkForLongClick(0, x, y);}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 buttonsif (!pointInView(x, y, mTouchSlop)) {// Outside buttonremoveTapCallback();if ((mPrivateFlags & PFLAG_PRESSED) != 0) {// Remove any future long press/tap checksremoveLongPressCallback();setPressed(false);}}break;}return true;}return false;
}
我们在 ACTION_DOWN 中看到checkForLongClick(0, x, y)方法 传入三个参数0,和x,y,接着看checkForLongClick方法
private void checkForLongClick(int delayOffset, float x, float y) {if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {mHasPerformedLongPress = false;if (mPendingCheckForLongPress == null) {mPendingCheckForLongPress = new CheckForLongPress();}mPendingCheckForLongPress.setAnchor(x, y);mPendingCheckForLongPress.rememberWindowAttachCount();postDelayed(mPendingCheckForLongPress,ViewConfiguration.getLongPressTimeout() - delayOffset);}
}
CheckForLongPress 实现了 Runnable 接口,然后通过
postDelayed发送消息
public boolean postDelayed(Runnable action, long delayMillis) {final AttachInfo attachInfo = mAttachInfo;if (attachInfo != null) {return attachInfo.mHandler.postDelayed(action, delayMillis);}// Postpone the runnable until we know on which thread it needs to run.// Assume that the runnable will be successfully placed after attach.getRunQueue().postDelayed(action, delayMillis);return true;
}
其实最后调用了handler 的postDelayed间隔 delayMillis 秒后发送消息,执行Runnable中的run方法,那我们看
Runnable中是如何实现的。
private final class CheckForLongPress implements Runnable {private int mOriginalWindowAttachCount;private float mX;private float mY;@Overridepublic void run() {if (isPressed() && (mParent != null)&& mOriginalWindowAttachCount == mWindowAttachCount) {if (performLongClick(mX, mY)) {mHasPerformedLongPress = true;}}}public void setAnchor(float x, float y) {mX = x;mY = y;}public void rememberWindowAttachCount() {mOriginalWindowAttachCount = mWindowAttachCount;}
}
看到调用了
performLongClick(mX, mY)方法并且, mHasPerformedLongPress = true;
再看performLongClick 干了啥呢
public boolean performLongClick() {return performLongClickInternal(mLongClickX, mLongClickY);
}
private boolean performLongClickInternal(float x, float y) {sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);boolean handled = false;final ListenerInfo li = mListenerInfo;if (li != null && li.mOnLongClickListener != null) {handled = li.mOnLongClickListener.onLongClick(View.this);}if (!handled) {final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);handled = isAnchored ? showContextMenu(x, y) : showContextMenu();}if (handled) {performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);}return handled;
}
到这里终于看到了,li.mOnLongClickListener.onLongClick(View.this) 长按事件响应了,过程是有点曲折不过流程算是走完了。总结下,先从view 的
dispatchTouchEvent 然后调用了 view 的 onTouchEvent 事件,然后在ontoucheEvent的action_down中调用
checkForLongClick方法既长按事件。
回到先前提的两个问题
问题1: 长按事件到底啥时执行我们已经知道了,但是按下后多久执行呢?
接着看:
触发checkForLongClick(0, x, y);时传进来第一个参数int类型的,字面意思是,延迟位移,
postDelayed(mPendingCheckForLongPress,ViewConfiguration.getLongPressTimeout() - delayOffset);
接着调用 postDelayed 其实后边的 ViewConfiguration.getLongPressTimeout() - delayOffset 就是handler发送消息延迟时间,现在偏移时间为0,那我们只要知道ViewConfiguration.getLongPressTimeout() 是多少就可以了。
public static int getLongPressTimeout() {return AppGlobals.getIntCoreSetting(Settings.Secure.LONG_PRESS_TIMEOUT,DEFAULT_LONG_PRESS_TIMEOUT);
}
private static final int DEFAULT_LONG_PRESS_TIMEOUT = 500;
默认的长按按压时间是500毫秒,现在再看我开始打log时打出的开始到触发长按,时间基本就是500了。
问题2:为啥点击事件不执行了
我们看到
MyButton-->onTouchEvent-->ACTION_UP
MyButton-->setOnClickListener
点击事件其实是整个事件最后执行的在onTouchEvent 的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) {mPerformClick = new PerformClick();}if (!post(mPerformClick)) {//点击事件在这里执行performClick();}}
}
mHasPerformedLongPress 这个好像在哪里看到过啊,是的,就在Runnable 方法的run方法里
@Override
public void run() {if (isPressed() && (mParent != null)&& mOriginalWindowAttachCount == mWindowAttachCount) {if (performLongClick(mX, mY)) {mHasPerformedLongPress = true;}}
}
由于长按事件先执行,触发了条件, mHasPerformedLongPress = true 所以当事件执行到action_up 时条件不满足了。这就是为啥有长按事件后点击事件不会执行。
这篇关于setOnTouchListener onTouchEvent setOnLongClickListener setOnClickListener 执行顺序及源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!