可能大家和我一样对于Android的事件分发机制总是停留在模模糊糊的表面上,但是在我们的项目中经常会用到比如解决事件的冲突,自定义下拉刷新的控件,如果我们知道了事件是如何的分发,那问题不就是很简单了,这时候就可以说It's so easy.最近才理清楚是怎么回事
先说一句,其实事件的分发机制最后都会在view上执行并且事件的分发都是从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 gesture
stopNestedScroll();
}
关键代码: if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//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;
}
}
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;
}
让我们看关键的代码就可以解决问题:在这里有两个比较关键的地方,li.mOnTouchListener.onTouch(this, event)和onTouchEvent(event),
我们可以看到当li.mOnTouchListener.onTouch(this, event) = false的时候,就会去执行onTouchEvent(event),
当li.mOnTouchListener.onTouch(this, event) = true的时候,就不会执行onTouchEvent(event)
那让我现在来思考一个问题:执行不执行onTouchEvent(event)对我们有什么影响么?
有一句话不是说实践大于理论,那现在我么你就可以拿着这个理论去实践一下,简单的Demo
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Demo", "button execute");
}
});
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("Demo", " onTouch execute== " + event.getAction());
return false;
}
});
运行结果:
哇哦,可以看到结果是先执行 onTouch(),之后再执行onClick()
这是我看见onTouch中返回值是false,那我改成true试试
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("Demo", " onTouch execute== " + event.getAction());
return false;
}
});
执行一下看见结果是:
突然发现怎么我的点击事件onClick()怎么没有执行呢?是不是很郁闷这时候我们就可以接着我们刚才的说了
onTouchEvent(event)对我们的执行的影响,为什么我们的onClick()在onTouch中返回值是true的时候就不执行了呢?
因为呀在dispatchTouchEvent(MotionEvent event) 的重点处,我们刚才说了,li.mOnTouchListener.onTouch(this, event)和onTouchEvent(event),当li.mOnTouchListener.onTouch(this, event) = true的时候就不会去执行onTouchEvent(event),通过我们刚才的测试,我们发现li.mOnTouchListener.onTouch(this, event) = true的时候我们的点击事件也没有执行,哇,那我们就可以假设点击事件就是在onTouchEvent(event)中处理的,现在就让我们去验证一下我们的假设,看看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;
}
}
重点代码1: 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 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)) {
重点代码2:performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.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 away
setPressed(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 buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
可以看见我标的重点2处:performClick()方法让我们进去看看
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
重点代码3: li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
原来藏得这么深,不过我们还是找到了,就在重点代码3处,好了,终于理清楚关系了
那就来总结一下onTouch()和onTouchEvent():
onTouch()直接影响到了onTouchEvent()方法
共同点:onTouch()和onTouchEvent()都在dispatchTouchEvent()方法中执行
不同点:1.如果onTouch()返回的是false,就会去执行onTouchEvent().此时的点击效果是有效的
因为点击事件肯定在onTouchEvent()中调用的
2.如果onTouch()返回的是true,就不会去执行onTouchEvent(),而是dispatchTouchEvent()自己消费
一般情况下我们都没有去调用onTouch()方法,所以呢,在源码中就会去调用onTouchEvent(),所以平时看到的点击事件是有效的
onTouchEvent()的源码分析:
在onTouchEvent()中对于不同事件的处理,比如按下,移动抬起,取消等不同事件的分别处理
看见在抬起的时候会执行performClick()来调用控件的点击事件
需要注意的是在onTouchEvent()中如果当前的控件是不可点击的,就直接返回false,就不会执行后续的action
因为判断的条件就是当前的控件是否可点击来执行action
总结就是:onTouch()返回值只是判断执行不执行onTouchEvent()方法,与action发生不发生没有关系
action的发生只和onTouchEvent()的返回值有关,onTouchEvent()的返回值又和当前的控件是否可以点击来决定的
如果想要action继续执行,就必须当前的控件是可以点击的
onTouch() 默认返回的值是flase就是意味着默认要去执行onTouchEvent()方法来追踪是哪一个action
以上就是对View的事件分发机制进行了个人的理解,接下来在讲讲VIewGroup的事件分发:
最开始我也说了,最后的事件分发都会在View上,为什么我这样说,我们现在自定义一个简单的View看一下
public class DemoLayout extends FrameLayout {
public DemoLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
}
mDemolayout = findViewById(R.id.my_layout);
button2 = findViewById(R.id.button2);
mDemolayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("Demo", "myLayout on touch");
return false;
}
});
主代码:
mDemolayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Demo", "You clicked my_layout");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Demo", "You clicked button2");
}
});
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<weitaomi.woyun.com.dispatchdemo.DemoLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/my_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
</weitaomi.woyun.com.dispatchdemo.DemoLayout>
看过了简单的代码以后我们来运行一下:看一下效果
可以看到button的点击事件执行了,而我们自定义控件的onTouch没有执行,让我们改变一下代码看看
public class DemoLayout extends FrameLayout {
public DemoLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
}
在自定义的view中加了一个方法,来看看我们点击button的效果:
怎么这时候我的button的点击事件没有执行呢?
我先来理理这个整体的过程:不过是VIewGroup还是VIew的事件分发都是从dispatchTouchEvent()开始的
不过传递的顺序都是从根布局开始传递的,就好比是父亲问儿子要不吃饭,儿子不吃就父亲就自己吃了,儿子吃的时候,父亲就给了它,对于我们写的这个Demo,Button的根布局是我们自定义的View,当我们点击Button的时候的执行顺序就是:
1.先去找根布局的dispatchTouchEvent(),也就是ViewGroup的dispatchTouchEvent()(自定义控件的dispatchTouchEvent()就是在ViewGroup中),所以让我们看看ViewGroup中的源码分析一下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
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;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// 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;
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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 = 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;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
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();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
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) {
// No touch targets so treat this as an ordinary view.
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;
}
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) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
重点2. handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
重点3. handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
看到ViewGroup中的 dispatchTouchEvent()比较长,但是我们只要我们想要的部分,我标记好的重点代码,看看是怎么回事?这里就是说当我们触摸的时候会调用dispatchTransformedTouchEvent()方法,我们在去dispatchTransformedTouchEvent里面探个究竟,
看到重点地方就是当ViewGroup有子view的时候就会调用重点3.处的代码,就是子View去调用自己的 dispatchTouchEvent(),这样就又回到了我们讲的View
当ViewGroup没有子View的时候,就会去调用重点2处的代码,ViewGroup的基类的dispatchTouchEvent(),因为ViewGroup的基类就是View,所以还是最终都会回到我们所讲事件的分发都会回到View的身上
好了总结一下流程:
事件的传递都是从dispatchTouchEvent()开始
* 根据ViewGroup源码中的dispatchTouchEvent()可以知道
*onInterceptTouchEvent() 直接影响到 ViewGroup中的在view执行不执行
*
* 总结就是:
* 1.onInterceptTouchEvent()返回的是false,就会去调用子view的dispatchTouchEvent()来处理事件
* 这时候走的就是button的dispatchTouchEvent()中,button是继承于view的
* 他的的dispatchTouchEvent()也就是view中的dispatchTouchEvent()方法
* 就会去走view的流程,需要注意的是只要当前的控件是可以点击的,child.dispatchTouchEvent() = true
* 所以此时ViewGroup就会返回true
* 2.onInterceptTouchEvent()返回的是true,就会去调用父类的dispatchTouchEvent(),而ViewGroup的父类就是
* view,所以这时候走的就是view的dispatchTouchEvent()来处理
*
*
* 在viewgroup中不管当前的onInterceptTouchEvent()是false还是true,最后都会走到view的dispatchTouchEvent()
* 只是此时的view是当前点击的控件的父类,还是当前点击的控件所在布局的基类
*
* 所以一句话就是ViewGroup中根据onInterceptTouchEvent()来判断执行操作,
以上都是个人理解,如果理解错误的地方希望大家不要喷哦