Android中View的事件分发和拦截机制

1.点击事件,就是MotionEvent,所谓点击事件的事件分发,其实就是对MotionEvent事件的分发过程。点击事件的分发过程由三个很重要的方法来共同完成:dispatchTouchEvent、 onInterceptTouchEvent和onTouchEvent.

下列的伪代码(Pseudo code)形象生动地展示了这三个方法之间的逻辑关系:

public boolean dispatchTouchEvent(MotionEvent event){
boolean consumed = false;
if(onInterceptTouchEvent(event)){
consumed= onTouchEvent(event);
}else{
consumed = child.dispatchTouchEvent(event);
}
return consumed;
}





2.传递规则: 


对于一个根ViewGroup来说,点击事件产生后,首先会传递给他,这时它的dispatchTouchEvent就会被调用,如果这个ViewGroup的onInterceptTouchEvent方法返回true,就表示它要拦截当前事件,接着这个ViewGroup就会处理这个事件,即onTouchEvent方法被调用,事件得到消耗;如果这个ViewGroup的onInterceptTouchEvent方法返回false就表示它不拦截当前事件,这时当前事件就会继续传递给他的子元素,接着子元素的dispatchTouchEvent方法就会被调用,如此反复直到事件被最终处理。


当一个点击事件产生后,它的传递过程遵循如下顺序Activity->Window->View,如果最终所有元素都没能处理这个时间,那么该事件最终将会被传递给Activity处理,即Activity的onTouchEvent方法被调用


注意:
1) ViewGroup默认不拦截任何事件, ViewGroup的onInterceptTouchEvent方法默认返回false
2) View没有onInterceptTouchEvent方法,一旦有点击事件传递给它,那么它的onTouchEvent方法就会被调用
3) View的onTouchEvent默认会消耗事件(返回true), 除非它是不可点击的
4) View的enable属性不影响onTouchEvent的默认返回值,哪怕一个View是disable状态,主要它的clickable或者longClickable有一个为true,那么它的onTouchEvent就返回true
5)事件传递过程是由外向内的,即事件总是先传递给父元素,然后再由父元素分发给子View,通过requestDisallowInterceptTouchEvent方法可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外

6)当某个View已经决定对事件进行拦截,那么同一事件序列内的所有事件都将交给它来处理,而且它的onInterceptTouchEvent方法将不再被调用



简而概之,事件的分发路径就是:activity -> window -> decor view -> view


3.源码分析


ViewGroup源码分析
public boolean dispatchTouchEvent(MotionEvent ev) {
    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();  //ACTION_DOWN事件将重置触控状态,所以FLAG_DISALLOW_INTERCEPT标记不会影响对该事件的拦截
	}
// Check for interception. final boolean intercepted;
	// First touch target in the linked list of touch targets. 触控对象列表的首个对象
	//mFirstTouchTarget 当ViewGroup的子元素成功处理事件时,该对象将被赋值并指向该子元素
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {  // FLAG_DISALLOW_INTERCEPT标记一旦被设置,则ViewGroup将无法拦截除了ACTION_DOWN事件外的所有触控事件

                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else { //当触控事件未发生时或事件由ViewGroup本身拦截时,则ViewGroup的onInterceptTouchEvent方法不会再被调用
            // There are no touch targets and this action is not an initial down
            // so this view group continues to intercept touches.
            intercepted = true;
        }

        ...
        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 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();
		//当ViewGroup不拦截事件时,事件将下发给它的子View去处理
                    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 (preorderedList != null) preorderedList.clear();
                }

                ...
            }
        }

        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {  //ViewGroup没有子元素或者处理事件的子元素在OnTouch方法中返回了false,此时ViewGroup自行处理事件
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } ...
	
    }
    ...
    return handled;
}

/**
 * Adds a touch target for specified child to the beginning of the list.
 * Assumes the target child is not already present.
 */
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) { //对mFirstTouchTarget进行赋值
    final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}


View的源码分析:

//view是单独的一个元素,它没有子元素,所以不能向下继续分发事件,只能自己处理事件

public boolean dispatchTouchEvent(MotionEvent event) {
    ...

    boolean result = false;
    ...
    if (onFilterTouchEventForSecurity(event)) {
        ...
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) { //这里先对OnTouchListener是否被设置进行判断
            result = true;
        }

        if (!result && onTouchEvent(event)) { //这里表明OnTouchListener优先级高于onTouchEvent,设置了listener,就不调用onTouchEvent方法
            result = true;
        }
    }

   ...

    return result;
}
 
 
public boolean onTouchEvent(MotionEvent event) {
    ...
    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.
	//这里表明即使处于disabled状态的view依然可以消耗触碰事件,只要Clickable或long_clickable其中之一为true
        return (((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
    }
    ...

    return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值