您的位置:首页 > 移动开发 > Android开发

Android事件分发详解

2017-03-30 13:06 309 查看

Android事件分发

1.事件传递的流程是从外到内,即事件总是由父元素分发给子元素:Activity->ViewGroup-View,但是通过requestDisallowInterceptTouchEvent可以使子view要求父view不拦截事件

2.当一个事件发生时,首先由Activity接收,然后activity会交由他的window处理,window的处理方式即是调用顶级容器DecorView(即setContentView所设置的View的父容器,是一个FramLayout)的dispatchTouchEvent方法,事件就进入了一个ViewGroup,开始按照事件分发机制去分发事件,若DecorView不处理,则activity会调用自身的onTouchEvent()方法消费事件

3.三个最主要方法:

public boolean dispatchTouchEvent(MotionEvent ev)

此方法是事件进入某个view和ViewGroup的入口,返回true表示在此层或者下层已经消费了事件,返回false则表示此层即下层都没处理

public boolean onTouchEvent(MotionEvent event)

此方法是view和ViewGroup自身事件的处理方法,返回true表示自己处理事件,返回false表示自己不处理

public boolean onInterceptTouchEvent(MotionEvent ev)

此方法是ViewGroup拦截事件的方法,返回true表示拦截事件不再向下层传递事件,返回false表示不拦截

4.整个ViewGroup的事件分发机制大致可以用下面的伪代码来表示:

public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
if(onInterceptTouchEvent(ev)){
handled = super.dispatchTouchEvent(ev);
}else{
if(child.dispatchTouchEvent(ev)){
handled = true;
}else{
handled = super.dispatchTouchEvent(ev);
}
}
return handled;
}


ViewGroup的dispatchTouchEvent方法的功能可分为两部分,即事件下发部分和自身事件处理部分,ViewGroup是继承于View,所以它的自身事件就是view的dispatchTouchEvent方法().

由两种情况来决定走什么功能:

1.是否拦截,拦截,则直接调用super.dispatchTouchEvent()方法处理身为一个view的特性处理自身事件。不拦截则调用child.dispatchTouchEvent()下发事件 2.所有被下发事件的子view的dispatchTouchEvent()在ACTION_DOWN就返回false,表示下面无view处理,则再调用super.dispatchTouchEvent()处理自身事件。这就完成了这一轮的事件分发,其他层同理,是一个递归的过程

3、一个事件从手指按下屏幕的那一刻到离开屏幕,中间还可能有多次滑动,这个过程以一个ACTION_DOWN开始,中间可能有0及以上个ACTION_MOVE,然后以一个ACTION_UP结束。这是一个事件序列。

4.事件的分发是一层一层分发下来的,一旦某个ViewGrou成功拦截了事件序列中的某个事件,那么此事件序列之后的所有事件都会默认被拦截(只要后续事件能传递到它这里),不会再去调用onInterceptTouchEvent询问是否拦截,当然也不会再向下分发,

5.如果一个事件传递到某个View或ViewGroup,一旦在ACTION_DOWN返回了false,那么此事件序列后续的事件都不会传递到这里了,并且父View的onTouchEvent方法会被调用即事件会再次向上传递,若一旦开始消费某个事件,那么即便在后续事件选择不消费了(比如此View的onTouchEvent方法在ACTION_DOWN返回true,但是ACTION_MOVE返回false),后续事件也会持续的传到这里,并且父View的onTouchEvent方法不会被调用即事件不会再次向上传递,这些后续被返回false的事件最终会直接传递给Activity处理

6.View.dispatchTouchEvent()关键代码,onTouchListener的优先级要高于onTouchEvent(),onClickListener在onTouchEvent()里面调用。:

if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}

if (!result && onTouchEvent(event)) {
result = true;
}


onTouchEvent方法里如果clickable和longClickable有一个为真,就会调用

performClick(),就是点击事件:

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;
}


7.Enable属性不影响默认的系统控件的onTouchEvent的返回值,只要view的clickable或longClickAble有一个为true,默认的onTouchEvent方法便会返回true,否则返回false(例如,当TextView的onTouchEvent默认返回false,因为它默认就是不可点击的,在设置了clickable为true后,它的onTouchEvent就返回true了)

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);
}


8.以ViewGroup为例,当事件传进来时,dispatchTouchEvent中的代码:

// 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;
}


这里的条件判断的决定是否直接将拦截标志位设为true,不再调用onInterceptTouchEvent方法去判断。满足条件为这个事件是ACTION_DOWN事件,或者mFirstTouchTarget不为空。ACTION_DOWN是一个新事件序列的开始肯定不能直接将拦截标志位设为true,而是要经过onInterceptTouchEvent去决定,mFirstTouchTarget是只要下面有子view消耗了事件就会赋值,所以不为空就是下面有子view处理了事件,而如果是后续事件但是mFirstTouchTarget为空说明子view在ACTION_DOWN事件就返回了false不消耗事件,那么后续的事件也就无需再传递给下面了,直接将拦截标志为设为true,而不再通过onInterceptTouchEvent去决定,这里需结合4和5仔细体会。

若进入了条件为真的的代码块,这个disallowIntercept一般是在子view中被用parent.requestDisallowInterceptTouchEvent后结果为true,就不再走onInterceptTouchEvent判断了,直接使拦截标志位位true,使得本parentView不拦截事件。虽然事件的分发是从外到里,但是这是特殊的子view干预父view的事件分发的办法,另外在MotionEvent.ACTION_DOWN事件到来时,disallowIntercept标志会在时被重置,mFirstTouchTarget会被清除,因为这是新事件序列的开始,所以这也更好理解为什么在MotionEvent.ACTION_DOWN时不能直接拦截了

// 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();
}


如果不拦截,就会遍历子view,通过是否在播放动画和事件是否落在它的范围内来获得合适的 View,如果存在就为mFirstTouchTarget赋值,注意这里能找到的合适子view可能不止一个,因此如果第一个合适的view不处理事件,那么会继续为下面合适的继续赋值,以此类推

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 = 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 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;
}
}
}


接着检验mFirstTouchTarget是否为空,为空的可能有两种,一是没有合适的view,二是view不处理事件:

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;
}
}


可以看到,不管是否为空都调用了dispatchTransformedTouchEvent()这个方法,看看它的关键代码

if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
return handled;


看到这里就能明白了,关键在于第三个参数,mFirstTouchTarget为空则将child赋值空,就会调用了父view的dispatchTouchEvent方法,事件再次向上传递,否则直接调用了子view的dispatchTouchEvent方法,事件进入下一轮

最后事件分发大致图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息