作为程序猿,最不想 看的但是也不得不去看的就是源码!所谓知其然也要知其所以然,神秘的大佬曾经说过进阶的方法就是READ THE FUCKING CODE!
负责集中处理所有类型设备的输入事件.我们对屏幕的点击,滑动,抬起等一系的动作都是由一个一个MotionEvent对象组成的。
主要事件类型
主要方法
上面这些是基本操作.下面我们来看一个小东西:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_test.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
Log.e("xfhy", "ACTION_DOWN")
}
MotionEvent.ACTION_MOVE -> {
Log.e("xfhy", "ACTION_MOVE")
}
MotionEvent.ACTION_UP -> {
Log.e("xfhy", "ACTION_UP")
}
else -> {
}
}
//返回false
false
}
btn_test.setOnClickListener {
Log.e("xfhy", "点击事件")
}
}
}
最后执行结果是
2018-10-15 17:51:19.766 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_DOWN
2018-10-15 17:51:19.785 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_MOVE
2018-10-15 17:51:19.844 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_MOVE
2018-10-15 17:51:19.844 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_UP
2018-10-15 17:51:19.848 9257-9257/com.xfhy.clickdemo E/xfhy: 点击事件
onClick()是在ACTION_UP之后才调用的.
至于为什么,稍后会给出解释(源码就是这样写的).
当一个MotionEvent产生后,需要分发给一个具体的View,去消化处理.我们需要去了解这个分发的过程.
下面有几个重要的方法,简单介绍一下:
下面是View事件分发流程图:
现在,我们队View的事件分发有了一个大致的了解.
上面的三个方法可以用以下伪代码来表示其关系:
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;//事件是否被消费
if (onInterceptTouchEvent(ev)){//调用onInterceptTouchEvent判断是否拦截事件
consume = onTouchEvent(ev);//如果拦截则调用自身的onTouchEvent方法
}else{
consume = child.dispatchTouchEvent(ev);//不拦截调用子View的dispatchTouchEvent方法
}
return consume;//返回值表示事件是否被消费,true事件终止,false调用父View的onTouchEvent方法
}
通过上面的介绍,差不多简单了解了事件的传递机制.下面我们来看看源码:
事件从最先到达Activity,我们来看一下Activity的dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//一个空方法,一般用于开发者想监听某个点击事件的开始
onUserInteraction();
}
//交给Window去分发
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//如果没人处理这个事件,那么当前Activity去处理
return onTouchEvent(ev);
}
上面是getWindow().superDispatchTouchEvent(ev).交给Window去分发事件.
然后Window只有一个实现类PhoneWindow,其实最后就是调用的PhoneWindow中的superDispatchTouchEvent(ev).
### PhoneWindow部分代码
private DecorView mDecor;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
咦,看到没有,其实是通过顶级View–DecorView去分发事件,嗯,很合乎常理.从上往下分配任务.
下面是DecorView的代码
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
再跟进super.dispatchTouchEvent(event);,就来到了ViewGroup(显然,DecorView是ViewGroup).
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
// 判断当前View是否没被遮盖住 如果是遮盖住了,则不进行事件分发
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//处理初次的按下事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous
// gesture
// due to an app switch, ANR, or some other state change.
//在开始新的触摸手势时丢弃所有先前的状态。
cancelAndClearTouchTargets(ev);
//重置所有触摸状态以准备新周期。
resetTouchState();
}
//检测拦截
final boolean intercepted;
//事件是按下
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
//判断是否禁止拦截 当子View调用requestDisallowInterceptTouchEvent(true)之后,这里的disallowIntercept就是true->禁止拦截 因为子类想接收这个事件并处理自己的逻辑
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) { //子类没有禁止拦截
//是否需要拦截事件 子类可以实现onInterceptTouchEvent()去很轻松的实现事件拦截
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
//检查是否已经被取消了
final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//如果没被取消 && 没有被拦截
if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS;
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
// a.如果View不可见并且没有播放动画
// b.点击事件的坐标落在View的范围内
// 满足a或者b则不分发事件给这个view
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
//子View已经接收触摸事件在自己的范围内,则直接跳出循环,将事件给它自己处理.
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//这里实际上是去调用child的dispatchTouchEvent(event);->子类去分发事件.
//ps: ViewGroup才能分发事件,View不能分发.
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
//子类想自己接收该事件(在自己的范围内)
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//将child赋值给mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
//如果某个child处理了事件,那么就不用继续循环了,直接跳出循环.
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null)
preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
//没有child接收该事件,则调用super.dispatchTouchEvent(event); 将该事件交给View去处理
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS);
}
return handled;
}
//在ViewGroup中,比View多了一个方法—onInterceptTouchEvent()方法,这个是干嘛用的呢,是用来进行事件拦截的,如果被拦截,事件就不会往下传递了,不拦截则继续。
//子类可以去实现这个方法,然后就可以轻松的拦截事件啦.
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;
}
/*
是否能收到事件: 如果可见或者没有播放动画
*/
private static boolean canViewReceivePointerEvents(@NonNull View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
上面是ViewGroup的分发事件源码,只抽取了源码的部分,关键部分加入了注释.
结论
ViewGroup会遍历所有子View去寻找能够处理点击事件的子View(可见,没有播放动画,点击事件坐标落在子View内部)最终调用子View的dispatchTouchEvent方法处理事件
当子View处理了事件则mFirstTouchTarget 被赋值,并终止子View的遍历。
如果ViewGroup并没有子View或者子View处理了事件,但是子View的dispatchTouchEvent返回了false(一般是子View的onTouchEvent方法返回false)那么ViewGroup会去处理这个事件(本质调用View的dispatchTouchEvent去处理)
下面来看一下View的dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent event) {
...
boolean result = false;
//如果窗口没有被遮盖
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
//监听事件
ListenerInfo li = mListenerInfo;
//这里的li.mOnTouchListener.onTouch(this, event)是有返回值的,如果是返回了true,那么result就是true了. 相当于处理了触摸事件
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//result为false时调用自己的onTouchEvent()去处理该事件.
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
return result;
}
从上面的代码中可以看出,如果设置了OnTouchListener并且onTouch方法返回了true,那么onTouchEvent不会被调用。
我们来看看onTouchEvent()方法
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
//CLICKABLE和LONG_CLICKABLE任何一个都可以消费该事件
//TextView默认是clickable是false,Button默认是true
//设置setOnClickListener()时会将clickable置为true
//设置setOnLongClickListener()时会将longClickable置为true
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
//即使View被设置成了不可用(setEnable(false)->DISABLED),但它还是可以消费点击事件
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:
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 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)) {
//在ACTION_UP 方法发生时,会触发performClick()方法.
performClick();
}
}
}
....
}
mIgnoreNextUpEvent = false;
break;
....
}
return true;
}
return false;
}
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;
}
所以,回调点击事件是在事件的最后Action_up中才去调用的.这也就解释了上面的demo中的最后才会调用回调点击事件的方法.
简单分析了一下View事件分发.希望能帮到大家.