ViewGroup的dispatchTouchEvent理解

ViewGroup的dispatchTouchEvent理解

以下图例子说明,OFramelayout在最外层

这里写图片描述

    图1.1 view的层级关系
  1. 结论1:
    dispatchTouchEvent()返回false,后续的ACTION_MOVE、ACTION_UP等收不到。注:dispatchTouchEvent()中判断手势是
    ACTION_DOWN时,返回false,则后续的触摸事件收不到,如果返回true,在后续的ACTION_MOVE条件下,不论返回什么都能收到后续触摸响应。类推,在onTouchEvent中是一样的结论。

  2. 结论2:
    如果有对应的OnTouchListener,可以在onTouch中返回true拦截事件,使onTouchEvent()不执行。

  3. 结论3:
    在一次触摸事件中,如果onInterceptTouchEvent()中返回true,则触摸事件由该视图消费,不会再派发。如果onInterceptTouchEvent()先返回false,然后在某个条件返回true,则在起初返回false到返回true之前,onInterceptTouchEvent()会被一直调用(前提条件是子视图消费了事件并返回了true),返回true后,onInterceptTouchEvent将不会再被调用,不管以后返回啥,onInterceptTouchEvent都不会再被调用。注:前提条件是该视图的dispatchTouchEvent要返回true,也就是说要能持续响应触摸事件。

看到这,大家都会觉得云里雾里,通过研读源码具体分析每个结论,以下基于android 5.1的源码。

结论一研读:

MFramelayout在dispatchTouchEvent()中的ACTION_DOWN条件下返回false,则触控事件首先进入OFramelayout的dispatchTouchEvent()即ViewGroup的dispatchTouchEvent()。进入1956行的判断,disallowIntercept是由requestDisallowInterceptTouchEvent()方法决定的。disallowIntercept为false时表示可拦截事件,然后会调用onInterceptTouchEvent()方法。disallowIntercept默认时为false。然后进入1985行的判断,由于是ACTION_DOWN,继续进入1995行,继续进入2007行,继续进入2016的for循环,进入2049的条件判断。进入dispatchTransformedTouchEvent()方法,在该方法的2405行,handled = child.dispatchTouchEvent(event),也就是调用了MFramelayout的dispatchTouchEvent()方法,由于假定条件下其返回false,dispatchTransformedTouchEvent()该方法返回false,这样就不会进入2049行的条件。然后进入到2090的条件判断,还是调用了dispatchTransformedTouchEvent()方法,然后执行super.dispatchTouchEvent(event),也就是执行View.dispatchTouchEvent()方法。关于View.dispatchTouchEvent(),请查看郭霖的博客。在OFramelayout的onTouchEvent中返回true,则2092行的handled为true,那么OFrameLayout的dispatchTouchEvent返回true。
接下来触摸事件是ACTION_MOVE,进入到OFrameLayout的dispatchTouchEvent()方法。进入到1968行,intercepted = true,则不会进入1985的条件判断,接下来进入2090行的条件判断。在这个过程中,OFrameLayout没将事件传给子视图。也就是dispatchTouchEvent()方法在ACTION_DOWN时返回false,则收不到后续的触摸事件,在这里就是MFramelayout收不到后续事件。

如果dispatchTouchEvent()方法在ACTION_DOWN时返回true,执行1960-》2092,ACTION_MOVE时执行1968-》2092。这里的数字代表android api22的ViewGroup中的行数

结论2研读:

查看郭霖的博客。Android事件分发机制完全解析,带你从源码的角度彻底理解(上),
相关结论:如果一个view的clickable是true,则该view的onTouchEvent返回的一定是true。
Android事件分发机制完全解析,带你从源码的角度彻底理解(下)

结论3研读

情况一:OFramelayout的onInterceptTouchEvent返回true。

OFrameLayout的dispatchTouchEvent()接受触控事件,ACTION_DOWN时会执行1960-》2092。mFirstTouchTarget为null,其赋值在2065行的addTouchTarget()方法中。ACTION_MOVE时执行1968-》2092。所以,在一次触摸事件中,如果onInterceptTouchEvent()中返回true,则触摸事件由该视图消费,不会再派发。

情况二:OFramelayout的onInterceptTouchEvent返回false。

ACTION_DOWN时,执行1960-》1985-》1995-》2049。
1、假设子视图消费了事件并返回了true,则会执行2065行,则mFirstTouchTarget被赋值为该子视图。
ACTION_MOVE是,在上面假设下,mFirstTouchTarget不为空,则会调用onInterceptTouchEvent()方法。执行顺序1960-》1985,由于是ACTION_MOVE,则不会进1995,接下来到2097-》2106,然后执行子视图(MFramelayout)的dispatchTouchEvent()方法。
2、如果子视图没有消费事件,则mFirstTouchTarget为空,则onInterceptTouchEvent()只会执行一次。
所以onInterceptTouchEvent()返回false,会被一直调用(前提条件是子视图消费了事件并返回了true)。

情况三:在一次触摸事件中,OFramelayout的onInterceptTouchEvent返回false,在某个条件再返回true。

在OFramelayout的onInterceptTouchEvent返回false时,详情参考情况二。在某个条件下onInterceptTouchEvent返回true时,假设先前子视图消费了事件并返回了true(即mFirstTouchTarget不为空),会执行1960-》2097-》2375-》2112,在2112行mFirstTouchTarget被赋值为null。触摸事件继续执行1968-》2092,onInterceptTouchEvent不会再被调用。
所以如果onInterceptTouchEvent()先返回false,然后在某个条件返回true,则在起初返回false时,onInterceptTouchEvent()会被一直调用(前提条件是子视图消费了事件并返回了true),返回true后,onInterceptTouchEvent将不会再被调用,不管以后返回啥,onInterceptTouchEvent都不会再被调用。

ViewGroup的dispatchTouchEvent源码

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

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

mFirstTouchTarget 有值,则一次触摸事件将一直由该值消费。

包含下拉刷新的控件触摸事件研究

1、问题:该控件重写onTouchEvent方法,如果ListView响应了触摸事件,该控件的onTouchEvent方法不会被调用,也就是说ListView滑动中,滑到显示第一条,再往下拉是拉不出下拉刷新头的。

2、问题:由于listview中执行了parent.requestDisallowInterceptTouchEvent(true);那么下拉刷新的控件是拦截不到触摸事件的,要怎样才能拦截?

答:在下拉刷新控件的dispatchTouchEvent()方法中执行requestDisallowInterceptTouchEvent(false);判断listview滚动到第一条完全显示时,判断是否是继续下拉,在dispatchTouchEvent()执行event.setAction(MotionEvent.ACTION_UP),使触摸结束,就会使mFirstTouchTarget 清空,然后event.setAction(MotionEvent.ACTION_DOWN)开启新的一次触摸事件,拦截事件就可以下拉出下拉头。

该研究源码展示:

package com.kedou.pulltofresh;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by xiaoshengke on 2016/8/30.
 */
public class RefreshLayout extends LinearLayout {
    /**
     * 下拉状态
     */
    public static final int STATUS_PULL_TO_REFRESH = 0;

    /**
     * 释放立即刷新状态
     */
    public static final int STATUS_RELEASE_TO_REFRESH = 1;

    /**
     * 正在刷新状态
     */
    public static final int STATUS_REFRESHING = 2;

    /**
     * 重置,刷新完成或未刷新状态
     */
    public static final int STATUS_RESET = 3;

    /**
     * 当前处理什么状态,可选值有STATUS_PULL_TO_REFRESH, STATUS_RELEASE_TO_REFRESH,
     * STATUS_REFRESHING 和 STATUS_RESET
     */
    private int currentStatus = STATUS_RESET;

    /**
     * 在被判定为滚动之前用户手指可以移动的最大值。
     */
    private int touchSlop;

    /**
     * 下拉头的View
     */
    private View header;

    /**
     * 需要去下拉刷新的ListView
     */
    private ListView listView;

    /**
     * 刷新时显示的进度条
     */
    private ProgressBar progressBar;

    /**
     * 指示下拉和释放的箭头
     */
    private ImageView arrow;

    /**
     * 指示下拉和释放的文字描述
     */
    private TextView description;

    /**
     * 上次更新时间的文字描述
     */
    private TextView updateAt;

    /**
     * 下拉头的布局参数
     */
    private MarginLayoutParams headerLayoutParams;

    /**
     * 下拉头的高度
     */
    private int hideHeaderHeight;

    /**
     * 是否获取下拉头的高度
     */
    private boolean isGetHeaderHeight;

    public RefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        header = LayoutInflater.from(context).inflate(R.layout.head_to_pull, null, true);
        progressBar = (ProgressBar) header.findViewById(R.id.progress_bar);
        arrow = (ImageView) header.findViewById(R.id.arrow);
        description = (TextView) header.findViewById(R.id.description);
        updateAt = (TextView) header.findViewById(R.id.updated_at);
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        setOrientation(VERTICAL);
        addView(header,0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(!isGetHeaderHeight){
            hideHeaderHeight = -getChildAt(0).getMeasuredHeight();
            headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
            headerLayoutParams.topMargin = hideHeaderHeight;
            listView = (ListView) getChildAt(1);
            isGetHeaderHeight = true;
        }
    }

    private boolean change;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        requestDisallowInterceptTouchEvent(false);  // 使该控件能够拦截事件
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
//                Log.e("Refresh:ACTION_DOWN","ACTION_DOWN");
                mDownY = ev.getRawY();
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_MOVE:
//                Log.e("Refresh:ACTION_MOVE","ACTION_MOVE");
                if(headerLayoutParams.topMargin <= hideHeaderHeight ){//去做结束一次触控,并开启一次新的触控
                    if(!change) {
                        change = true;
                        headerLayoutParams.topMargin = hideHeaderHeight;
                        ev.setAction(MotionEvent.ACTION_UP);
                        super.dispatchTouchEvent(ev);
                        ev.setAction(MotionEvent.ACTION_DOWN);
                        return super.dispatchTouchEvent(ev);
                    }
                }else{
                    change = false;
                }
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_UP:
//                Log.e("Refresh:ACTION_UP","ACTION_UP");
                return super.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
//        Log.e("action_move","actionmove");
//        return true;
        if (!canToPull()) {
            return false;
        }

        final int action = ev.getAction();

        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            mIsBeingDragged = false;
            return false;
        }

        if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) {
            return true;
        }
        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (canToPull()) {
                    float deltaY = ev.getRawY() - mDownY;
                    // 如果手指是下滑状态,并且下拉头是完全隐藏的,就屏蔽下拉事件
                    if (deltaY <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
                        return false;
                    }
                    if (deltaY < touchSlop) {
                        return false;
                    }
                    if(Math.abs(deltaY) > touchSlop){
                        mIsBeingDragged = true;
                    }
                    mDownY = ev.getRawY();  //拦截事件后onInterceptTouchEvent不会再被调用,也就是说这里只会执行一次。
                }
                break;
            }
            case MotionEvent.ACTION_DOWN: {
                if (canToPull()) {
                    mDownY = ev.getRawY();
                    mIsBeingDragged = false;
                }
                break;
            }
        }

        return mIsBeingDragged;
    }

    private float mDownY;
    private boolean mIsBeingDragged;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int actionMasked = event.getActionMasked();
        switch(actionMasked){
            case MotionEvent.ACTION_DOWN:
                mDownY = event.getRawY();
                Log.e("mDownY",mDownY+"");
                break;
            case MotionEvent.ACTION_MOVE:
                float deltaY = event.getRawY() - mDownY;
                Log.e("deltaY",deltaY+":::"+mDownY);
                if(Math.abs(deltaY) > touchSlop){
                    mIsBeingDragged = true;
                }
                if(mIsBeingDragged){
                    if(canToPull()) {
                        moveRefreshHeader(deltaY);  //下拉出下拉头

                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                resetRefreshHeader();
        }
        return true;
    }

    private void resetRefreshHeader() {
        headerLayoutParams.topMargin = hideHeaderHeight;
        header.setLayoutParams(headerLayoutParams);
    }

    private void moveRefreshHeader(float deltaY) {
        // 通过偏移下拉头的topMargin值,来实现下拉效果
        headerLayoutParams.topMargin = (int) ((deltaY / 2) + hideHeaderHeight);
        header.setLayoutParams(headerLayoutParams);
    }

    /**
     * 能够下拉
     * @return
     *  true为能够下拉
     */
    public boolean canToPull(){
        View one = listView.getChildAt(0);
        if(one != null){
            if(listView.getFirstVisiblePosition() == 0 &&
                    one.getTop() >= 0) {
                return true;
            }
        }else{
            return true;
        }
        return false;
    }

}

研究缩写的源码:dispatchTouchEvent研究源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值