为了更好的研究View的事件转发,我们自定以一个MyButton继承Button,然后把跟事件传播有关的方法进行复写,然后添加上日志:
然后把我们自定义的按钮加到主布局文件中:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <myview.MyLinerLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <myview.MyButton android:id="@+id/btn" android:layout_width="100dp" android:layout_height="100dp" android:text="Button" /> </myview.MyLinerLayout> </LinearLayout>
在Activity中设置Button的Touch事件:
public class MainActivity extends Activity { protected static final String TAG = "MyButton"; private Button mButton ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.id_btn); mButton.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: Log.e(TAG, "onTouch ACTION_DOWN"); break; case MotionEvent.ACTION_MOVE: Log.e(TAG, "onTouch ACTION_MOVE"); break; case MotionEvent.ACTION_UP: Log.e(TAG, "onTouch ACTION_UP"); break; default: break; } return false; } }); } }
点击按钮之后查看打印结果:
E/MyButton(879): dispatchTouchEvent ACTION_DOWN
E/MyButton(879): onTouch ACTION_DOWN
E/MyButton(879): onTouchEvent ACTION_DOWN
E/MyButton(879): dispatchTouchEvent ACTION_MOVE
E/MyButton(879): onTouch ACTION_MOVE
E/MyButton(879): onTouchEvent ACTION_MOVE
E/MyButton(879): dispatchTouchEvent ACTION_UP
E/MyButton(879): onTouch ACTION_UP
E/MyButton(879): onTouchEvent ACTION_UP
可以看到,不管是DOWN,MOVE,UP都会按照下面的顺序执行
1、dispatchTouchEvent
2、 setOnTouchListener的onTouch
3、onTouchEvent
先来看触摸事件的入口函数:
public boolean dispatchTouchEvent(MotionEvent event) { if (!onFilterTouchEventForSecurity(event)) { return false; } if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && mOnTouchListener.onTouch(this, event)) { return true; } return onTouchEvent(event); }
可以看出如果mOnTouchListener不为空,并且view是ENABLED的,并且mOnTouchListener.onTouch(this, event)的返回值==true,那么
dispatchTouchEvent的返回值就是true,onTouchEvent方法就得不到执行。
public void setOnTouchListener(OnTouchListener l) { mOnTouchListener = l; }
如果view设置了setOnTouchListener的监听,那么mOnTouchListener!=null就成立,一般view是ENABLED的,所以onTouch函数的返回值就决定了onTouchEvent函数能否得到执行。
来看下onTouchEvent函数的源码:
public boolean onTouchEvent(MotionEvent event) { final int viewFlags = mViewFlags; //如果当前View是Disabled状态且是可点击则会消费掉事件(return true);可以忽略,不是我们的重点 if ((viewFlags & ENABLED_MASK) == DISABLED) { return (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } // if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { switch (event.getAction()) { case MotionEvent.ACTION_UP: boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; if ((mPrivateFlags & 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 (!mHasPerformedLongPress) { // 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) { mPrivateFlags |= PRESSED; refreshDrawableState(); postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!post(mUnsetPressedState)) { // If the post failed, unpress right now mUnsetPressedState.run(); } removeTapCallback(); } break; case MotionEvent.ACTION_DOWN: if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } mPrivateFlags |= PREPRESSED; mHasPerformedLongPress = false; postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); break; case MotionEvent.ACTION_CANCEL: mPrivateFlags &= ~PRESSED; refreshDrawableState(); removeTapCallback(); break; case MotionEvent.ACTION_MOVE: final int x = (int) event.getX(); final int y = (int) event.getY(); // Be lenient about moving outside of buttons int slop = mTouchSlop; if ((x < 0 - slop) || (x >= getWidth() + slop) || (y < 0 - slop) || (y >= getHeight() + slop)) { // Outside button removeTapCallback(); if ((mPrivateFlags & PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); // Need to switch from pressed to not pressed mPrivateFlags &= ~PRESSED; refreshDrawableState(); } } break; } return true; } return false; }
首先分析down事件:
可以看到down的时候会将mPrivateFlags设置一个PREPRESSED的表示,设置mHasPerformedLongPress=false;表示长按事件还未触发
这是一个延迟115ms的异步任务,也就是115ms之后就会执行CheckForTap类中的run()方法。
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
private final class CheckForTap implements Runnable { public void run() { mPrivateFlags &= ~PREPRESSED; mPrivateFlags |= PRESSED; refreshDrawableState(); if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { postCheckForLongClick(ViewConfiguration.getTapTimeout()); } } }
将mPrivateFlags设置为PRESSED 里面还包含了一个postCheckForLongClick()的方法,来看下postCheckForLongClick()方法:
private void postCheckForLongClick(int delayOffset) { mHasPerformedLongPress = false; if (mPendingCheckForLongPress == null) { mPendingCheckForLongPress = new CheckForLongPress(); } mPendingCheckForLongPress.rememberWindowAttachCount();
//执行一个延迟500-115ms异步任务 postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout() - delayOffset); }
class CheckForLongPress implements Runnable { private int mOriginalWindowAttachCount; public void run() { if (isPressed() && (mParent != null) && mOriginalWindowAttachCount == mWindowAttachCount) { if (performLongClick()) { mHasPerformedLongPress = true; } } }
如果performLongClick()返回true那么mHasPerformedLongPress=true。
public boolean performLongClick() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); boolean handled = false; if (mOnLongClickListener != null) { // 回调用户实现的长按操作监听函数(OnLongClickListener) handled = mOnLongClickListener.onLongClick(View.this); } if (!handled) { // 如果OnLongClickListener的onLongClick返回false // 则需要继续处理该长按事件,这里是显示上下文菜单 handled = showContextMenu(); } if (handled) { // 长按操作事件被处理了,此时应该给用户触觉上的反馈 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } return handled; }
可以看到用户的长按事件是在这个方法里面实现的回调,并且返回一个boolean值。
总结下就是:
当用户按下,首先会设置标识为PREPRESSED,如果115后,没有抬起,会将View的标识设置为PRESSED且去掉PREPRESSED标识,然后发出一个检测长按的延迟任务,延时为:ViewConfiguration.getLongPressTimeout() - delayOffset(500ms -115ms),这个115ms刚好是检测到PREPRESSED时间;也就是用户从DOWN触发开始算起,如果500ms内没有抬起则认为触发了长按事件。
在来看下up事件:
如果包含PRESSED或者PREPRESSED则进入执行体,也就是无论是115ms内或者之后抬起都会进入执行体,如果mHasPerformedLongPress==false,进入IF,否则直接跳出。
如果mPerformClick为null,初始化一个实例,然后立即通过handler添加到消息队列尾部,如果添加失败则直接执行 performClick();添加成功,在mPerformClick的run方法中就是执行performClick()方法。
public boolean performClick() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); if (mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); mOnClickListener.onClick(this); return true; } return false; }
可以看到这个方法里面会执行用户的onClick()的回调,并且返回true,表示消费了这个事件。
总结下up事件:如果用户设置了长按回调并且返回了true,那么performClick()方法就不会执行,那么我们的onClick()方法也就不会执行。
总结下整个的onTouchEvent方法,只要view具有onClick或者onLongClick那么都会返回true,否则返回false。这也就是Button可以不用设置点击或者长按的回调,而TextView需要设置回调之后
才会进入里面的if()体的原因:
public void setOnClickListener(@Nullable OnClickListener l) { if (!isClickable()) { setClickable(true); } getListenerInfo().mOnClickListener = l; }
调用这个方法之后,如果不可点击就会设置成可以点击。
整个View的事件转发流程是:
View.dispatchEvent->View.setOnTouchListener->View.onTouchEvent
在dispatchTouchEvent中会进行OnTouchListener的判断,如果OnTouchListener不为null且返回true,则表示事件被消费,onTouchEvent不会被执行;否则执行onTouchEvent。