关于Android点击事件派发的资料,网上已是大把,但是自己分析总结的,显得更加深刻。Come on!
首先,我们编辑一个简单的小程序
上项目代码:
public class MainActivity extends Activity {
private final String TAG = "click";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "------window:" + getWindow());
Button btn = (Button) findViewById(R.id.btn);
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "------onTouch:" + event.getAction());
return false;
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "------onClick");
}
});
}
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d(TAG, "------dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
}
运行结果:
09-02 16:02:32.071 1836-1836/com.cxy.test D/click﹕ ------window:com.android.internal.policy.impl.PhoneWindow@534687e4
09-02 16:02:34.251 1836-1836/com.cxy.test D/click﹕ ------dispatchTouchEvent
09-02 16:02:34.251 1836-1836/com.cxy.test D/click﹕ ------onTouch:0
09-02 16:02:34.387 1836-1836/com.cxy.test D/click﹕ ------dispatchTouchEvent
09-02 16:02:34.387 1836-1836/com.cxy.test D/click﹕ ------onTouch:1
09-02 16:02:34.407 1836-1836/com.cxy.test D/click﹕ ------onClick
从这个log来看,我们可以看到最先执行了Activity的dispatchTouchEvent方法,然后onTouch,然后接着循环一遍,最后再是执行按钮的点击事件。疑问来了,为啥莫dispatchTouchEvent和onTouch都执行了两次,onClick才执行了一次?两次的onTouch都不一样,0和1是啥莫概念?
带着疑问,让我们进入MotionEvent看看里边是如何定义变量的:
public static final int ACTION_DOWN = 0; //按下
public static final int ACTION_UP = 1; //抬起
public static final int ACTION_MOVE = 2; //手势移动
如此甚是清晰,这个例子当中,我们只是简单的按下、抬起,并没有别的操作,因此有两次touch操作,分别对应着0和1。
接下来我们来看下另外一个场景
让onTouch方法返回true,再次点击按钮输出log:
09-02 16:02:32.071 1836-1836/com.cxy.test D/click﹕ ------window:com.android.internal.policy.impl.PhoneWindow@534687e4
09-02 16:02:34.251 1836-1836/com.cxy.test D/click﹕ ------dispatchTouchEvent
09-02 16:02:34.251 1836-1836/com.cxy.test D/click﹕ ------onTouch:0
09-02 16:02:34.387 1836-1836/com.cxy.test D/click﹕ ------dispatchTouchEvent
09-02 16:02:34.387 1836-1836/com.cxy.test D/click﹕ ------onTouch:1
这里我们看到了,onClick没有执行了,那是为啥莫呢?让我们记住这个疑问,接着继续分析吧。
Android点击事件的派发机制
首先,我们了解下Activity中的window,从上面的程序运行Log
------window:com.android.internal.policy.impl.PhoneWindow
可以知道,每一个Activity都对应有一个Window
当一个点击操作发生时,最先传递给Activity进行处理,由它的dispatchTouchEvent方法触发
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction(); // 这是一个空函数,啥也没干
}
// 这里交由Activity内部的window进行处理,如果返回true,意味着整个事件就结束了
// 返回false意味着没人去处理,所有view的onTouchEvent都返回了false,最终由Activity去处理
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// 在这里,Activity的onTouchEvent被调用
return onTouchEvent(ev);
}
我们来看看Window中的superDispatchTouchEvent:
/**
* Used by custom windows, such as Dialog, to pass the touch screen event
* further down the view hierarchy. Application developers should
* not need to implement or call this.
*
*/
public abstract boolean superDispatchTouchEvent(MotionEvent event);
这里是一个抽象函数,还告诉我们不要去重写它,貌似更蒙了,不着急,在先前的程序中,我们知道了
com.android.internal.policy.impl.PhoneWindow是Window的实现。接下来,我们就到这个类中看看
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
这里,PhoneWindow是把事件交由DecorView去处理了,这个DecorView又是啥玩意儿?
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
}
DecorView继承自FrameLayout,所以最终的事件将会传到我们的View,至于为什么不用去纠结太多,不然我们的应用怎么去响应点击事件呢。最重要的是我们要理解当事件传到我们的根View之后,又是如何传递的?下面我们来逐步解答。
根View对点击事件的分发机制:
点击事件到达了根View之后,会去调用ViewGroup的dispatchTouchEvent方法,接下来的代码可能比较繁琐,请大家耐心看看,关键点做了注释。让我们先了解其中是如何操作的:如果根View拦截了,即intercepted=true,则事件有ViewGroup处理就行了,这里如果ViewGroup的mOnTouchListener被设置了,那么onTouch方法将被调用,如果没设置,onTouchEvent将被调用,如果你两个方法都设置了,那么onTouch将会覆盖onTouchEvent,只执行了onTouch。(哈哈,这里也解决了上边的疑问了吧)接下来要说明的一点是,ViewGroup默认是不拦截点击事件的。如果根View不拦截事件,那么事件就会流到子View上,这个时候,子View的dispatchTouchEvent方法将被调用。一层一层,如此循环,直至完成了整个事件的派发。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
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();
}
// Check for interception.
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); // 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;
}
// Check for cancelation.
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;
// 在这里将事件派发至子View,前提是intercepted=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;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
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 = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// 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);
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();
// 这里将点击事件派发到子view当中
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
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.
// 这里是ViewGroup拦截了事件,或者是子View的onTouchEvent都返回了false,全权有ViewGroup去处理这一切
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 这里是ViewGroup对点击事件的处理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
接下来,我们看看ViewGroup对点击事件的处理:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
// 这里就是调用了View的dispatchTouchEvent方法。
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
View中的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent event) {
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;
}
}
这代码大概讲的就是,mOnTouchListener为空时,调用onTouchEvent,反之,mOnTouchListener不为空时,调用onTouch,而我们常用的onClick方法是在onTouchEvent里头通过performClick触发了,具体代码太多就不贴了。请注意此状况的前提:ViewGroup拦截了事件,或者是子View的onTouchEvent都返回了false。