基础认识
1、touch事件
- MotionEvent:封装事件相关的细节(touch的位置、时间等)
- 事件的类型
事件类型 |
具体动作 |
ACTION_DOWN |
按下View(所有事件的开始) |
ACTION_MOVE |
滑动View |
ACTION_UP |
抬起View(与DOWN对应) |
ACTION_CANCEL |
结束事件(非人为原因) |
2、touch事件传递
- 传递的对象:Activity、ViewGroup、View
- 传递的顺序:Activity -> ViewGroup -> View
- 相关的方法:
方法 |
作用 |
调用时机 |
dispatchTouchEvent() |
分发touch事件 |
当事件传递到当前view的时候调用 |
onInterceptTouchEvent() |
拦截touch事件 |
dispatchTouchEvent()内部调用 |
onTouchEvent() |
处理touch事件 |
dispatchTouchEvent()内部调用 |
源码分析
1.Activity事件分发源码
- 涉及到的方法:dispatchTouchEvent()和onTouchEvent()。
- 一个点击事件发生时,事件最先传到Activity的dispatchTouchEvent()进行事件分发。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
//1、onUserInteraction()
//(1)当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法
public void onUserInteraction() {}
//2、getWindow().superDispatchTouchEvent(ev)
//(1)getWindow() == PhoneWindow
//(2)调用的是PhoneWindow的superDispatchTouchEvent
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
//(1)DecorView继承自FrameLayout,是所有界面的父类
//(2)FrameLayout是ViewGroup的子类,故DecorView的间接父类 = ViewGroup
//(3)到这里即将事件传递给ViewGroup去分发了
class DecorView extends FrameLayout{}
//3、onTouchEvent(ev)
//(1)当一个点击事件未被Activity下任何一个View接收处理时
//(2)只有在点击事件在Window边界外才会返回true,一般情况都返回false
public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
//处理边界外点击事件的判断:是否是DOWN事件,event的坐标是否在边界内等
public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
if (mCloseOnTouchOutside && event.getAction() == MotionEvent.ACTION_DOWN
&& isOutOfBounds(context, event) && peekDecorView() != null) {
return true;
}
return false;
}
- 总结:当activity接收到事件时,事件的起始事件一般都是ACTION_DOWN,所以必然会执行分发事件前的方法做一些预处理等等;然后就会分发给子view去处理,如果没有子view处理,activity的onTouchEvent就会判断是否在边界内等条件来决定是自己处理还是不处理。
2、ViewGroup事件分发源码
- 涉及到的方法:dispatchTouchEvent()、onInterceptTouchEvent()、onTouchEvent()
//内容比较多,这里仅分析关键部分
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
......
boolean handled = false;
......
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//1.新事件开始的时候,清除原来保存的状态
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
//2.是否禁用事件拦截的功能(默认是false)
//可通过调用requestDisallowInterceptTouchEvent()修改
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null){
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//事件拦截下面会详细讲
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action);
} else {
intercepted = false;
}
} else {
intercepted = true;
}
......
//3.判断是否是取消事件
final boolean canceled = resetCancelNextUpFlag(this)|| actionMasked == MotionEvent.ACTION_CANCEL;
......
//4.如果不是取消事件并且没有被拦截
//则记录事件的位置,并倒序遍历子view,找到接收事件的view并记录下来
if (!canceled && !intercepted) {
......
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
for (int i = childrenCount - 1; i >= 0; i--) {
.......
}
}
//5.最终会调到dispatchTransformedTouchEvent来做事件的分发或者处理
if (mFirstTouchTarget == null) {
handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
} else {
......
if (dispatchTransformedTouchEvent(ev, cancelChild,target.child, target.pointerIdBits)) {
handled = true;
}
......
}
......
return handled;
}
//下面是ViewGroup的默认实现,可以重写此方法来自定义事件是否拦截
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
//(1)如果child为空即没有view接收处理,则返回给父view处理
//(2)如果child不为空,则交由子view继续分发事件
//(3)因为ViewGroup extends View;
// 所以super.dispatchTouchEvent()即View.dispatchTouchEvent();
// 因此会执行ViewGroup继承来的onTouch() -> onTouchEvent() -> performClick()
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits) {
......
final MotionEvent transformedEvent;
......
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
handled = child.dispatchTouchEvent(transformedEvent);
}
......
return handled;
}
- 总结:首先会判断事件的类型,如果是ACTION_DOWN则会清除前一次记录的Target和Status。接下来就会去判断是否拦截或者取消事件;如果拦截则不向下传递而调用父类的事件分发,最终执行自己继承来的touch事件处理流程;如果不拦截则遍历子view来寻找接收者,如果过找到则交由子view处理,如果找不到则同拦截流程处理。
3、View事件分发源码
- 涉及到的方法:dispatchTouchEvent()、onTouchEvent()
public boolean dispatchTouchEvent(MotionEvent event) {
......
boolean result = false;
......
if (onFilterTouchEventForSecurity(event)) {
//拖曳事件的处理
if ((mViewFlags & ENABLED_MASK) == ENABLED
&& handleScrollBarDragging(event)) {
result = true;
}
//这里需要满足三个条件
//(1)mOnTouchListener != null
//(2)当前点击的控件是否enable
//(3)mOnTouchListener.onTouch() == true
ListenerInfo li = mListenerInfo;
if (li != null
&& li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//没有拖拽监听也没有事件监听才会会执行onTouchEvent()
if (!result && onTouchEvent(event)) {
result = true;
}
}
......
return result;
}
//返回true,则处理了此事件
//返回false,不处理此事件
public boolean onTouchEvent(MotionEvent event) {
......
//1、有touch代理则交给代理处理
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
//2、先判断有没有设置事件监听,然后根据事件类型做相应处理
if (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
//(1)ACTION_UP主要处理view的OnClickListener
case MotionEvent.ACTION_UP:
......
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
removeLongPressCallback();
if (!focusTaken) {
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
......
break;
//(2)主要处理view的OnLongClickListener
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
......
boolean isInScrollingContainer = isInScrollingContainer();
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap,ViewConfiguration.getTapTimeout());
} else {
setPressed(true, x, y);
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
......
break;
//(3)处理view的滑动事件
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
if (!pointInView(x, y, mTouchSlop)) {
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
//OnClickListener事件
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;
}
//mOnLongClickListener事件,默认500毫秒为LongClick
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;
}
- 总结
- 监听事件的执行顺序:Dragging(event) -> OnTouchListener(onTouch) -> Delegate -> OnLongClickListener(ACTION_DOWN) -> OnClickListener(ACTION_UP)