欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

程序员文章站 2022-04-14 23:19:23
什么是事件?事件是用户触摸手机屏幕,引起的一系列TouchEvent,包括ACTION_DOWN、ACTION_MOVE、ACTION_UP、ACTION_CANCEL等,这些action组合后变成点击事件、长按事件等。 在这篇文章中,用打Log测试的方法来了解Android TouchEvent ......

什么是事件?事件是用户触摸手机屏幕,引起的一系列touchevent,包括action_down、action_move、action_up、action_cancel等,这些action组合后变成点击事件、长按事件等。

在这篇文章中,用打log测试的方法来了解android touchevent 事件分发,拦截,处理过程。虽然看了一些其他的文章和源码及相关的资料,但是还是觉得需要打下log和画图来了解一下,不然很容易忘记了事件传递的整个过程。所以写下这篇文章,达到看完这篇文章基本可以了解整个过程,并且可以自己画图画出来给别人看。

先看几个类,主要是画出一个3个viewgroup叠加的界面,并在事件分发、拦截、处理时打下log.

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

github地址:https://github.com/libill/toucheventdemo

一、通过打log分析事件分发

这里在一个activity上添加三个viewgroup来分析,这里值得注意的是activity、view是没有onintercepttouchevent方法的。

一、了解activity、viewgroup1、viewgroup2、viewgroup3四个类

  1. activity_main.xml

     <?xml version="1.0" encoding="utf-8"?>
         <android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context="com.touchevent.demo.myactivity">
         <com.touchevent.demo.viewgroup1
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@color/coloraccent">
         <com.touchevent.demo.viewgroup2
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_margin="50dp"
             android:background="@color/colorprimary">
             <com.touchevent.demo.viewgroup3
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:layout_margin="50dp"
                 android:background="@color/colorprimarydark">
             </com.touchevent.demo.viewgroup3>
         </com.touchevent.demo.viewgroup2>
         </com.touchevent.demo.viewgroup1>
     </android.support.constraint.constraintlayout>  
  2. 主界面:mainactivity.java

     public class myactivity extends appcompatactivity {
         private final static string tag = myactivity.class.getname();
    
         @override
         protected void oncreate(bundle savedinstancestate) {
             super.oncreate(savedinstancestate);
             setcontentview(r.layout.activity_main);
         }
    
         @override
         public boolean dispatchtouchevent(motionevent ev) {
             log.i(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev));
             boolean superreturn = super.dispatchtouchevent(ev);
             log.d(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
             return superreturn;
         }
    
         @override
         public boolean ontouchevent(motionevent ev) {
             log.i(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev));
             boolean superreturn = super.ontouchevent(ev);
             log.d(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
             return superreturn;
         }
     }
  3. 三个viewgroup,里面的代码完全一样:viewgroup1.java,viewgroup2.java,viewgroup3.java。由于代码一样所以只贴其中一个类。

     public class viewgroup1 extends linearlayout {
         private final static string tag = viewgroup1.class.getname();
    
         public viewgroup1(context context) {
             super(context);
         }
    
         public viewgroup1(context context, attributeset attrs) {
             super(context, attrs);
         }
    
         @override
         public boolean dispatchtouchevent(motionevent ev) {
             log.i(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev));
             boolean superreturn = super.dispatchtouchevent(ev);
             log.d(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
             return superreturn;
         }
    
         @override
         public boolean onintercepttouchevent(motionevent ev) {
             log.i(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev));
             boolean superreturn = super.onintercepttouchevent(ev);
             log.d(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
             return superreturn;
         }
    
         @override
         public boolean ontouchevent(motionevent ev) {
             log.i(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev));
             boolean superreturn = super.ontouchevent(ev);
             log.d(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
             return superreturn;
         }
     }

二、不拦截处理任何事件

添加没有拦截处理任何事件的代码,看看事件是怎么传递的,选择info,查看log.

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

从流程图可以看出,事件分发从activity开始,然后分发到viewgroup,在这个过程中,只要viewgroup没有拦截处理,最后还是会回到activity的ontouchevent方法。

三、viewgroup2的dispatchtouchevent返回true

把viewgroup2.java的dispatchtouchevent修改一下,return 返回true使事件不在分发

@override
public boolean dispatchtouchevent(motionevent ev) {
 log.i(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev));
 log.d(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev) + " " + true);
 return true;
}

此时的log

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

一文读懂 Android TouchEvent 事件分发、拦截、处理过程

从图片可以看出,当viewgroupon2的dispatchtouchevent返回true后,事件不会再分发传送到viewgroup3了,也不会分发到activity的ontouchevent了。而是事件到了viewgroupon2的dispatchtouchevent后,就停止了。dispatchtouchevent返回true表示着事件不用再分发下去了。

四、viewgroup2的onintercepttouchevent返回true

把viewgroup2.java的onintercepttouchevent修改一下,return 返回true把事件拦截了

@override
public boolean dispatchtouchevent(motionevent ev) {
    log.i(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev));
    boolean superreturn = super.dispatchtouchevent(ev);
    log.d(tag, "dispatchtouchevent    action:" + stringutils.getmotioneventname(ev) + " " + superreturn);
    return superreturn;
}

@override
public boolean onintercepttouchevent(motionevent ev) {
    log.i(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev));
    log.d(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev) + " " + true);
    return true;
}

此时的log

一文读懂 Android TouchEvent 事件分发、拦截、处理过程
一文读懂 Android TouchEvent 事件分发、拦截、处理过程

可以看出viewgroup2拦截了事件,就不会继续分发到viewgroup3;而且viewgroup3拦截了事件又不处理事件,会把事件传递到activity的ontouchevent方法。

五、viewgroup2的onintercepttouchevent、ontouchevent返回true

把viewgroup2.java的ontouchevent修改一下,return 返回true把事件处理了

@override
public boolean onintercepttouchevent(motionevent ev) {
    log.i(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev));
    log.d(tag, "onintercepttouchevent action:" + stringutils.getmotioneventname(ev) + " " + true);
    return true;
}

@override
public boolean ontouchevent(motionevent ev) {
    log.i(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev));
    log.d(tag, "ontouchevent          action:" + stringutils.getmotioneventname(ev) + " " + true);
    return true;
}

一文读懂 Android TouchEvent 事件分发、拦截、处理过程
一文读懂 Android TouchEvent 事件分发、拦截、处理过程

从流程可以总结出,当viewgroup2的onintercepttouchevent、ontouchevent都返回true时,事件最终会走到viewgroup2的ontouchevent方法处理事件,后续的事件都会走到这里来。

上面通过log分析很清楚了,是不是就这样够了?其实还不行,还要从源码的角度去分析下,为什么事件会这样分发。

二、通过源码分析事件分发

一、activity的dispatchtouchevent

先看看activity下的dispatchtouchevent

public boolean dispatchtouchevent(motionevent ev) {
    if (ev.getaction() == motionevent.action_down) {
        onuserinteraction();
    }
    if (getwindow().superdispatchtouchevent(ev)) {
        return true;
    }
    return ontouchevent(ev);
}

onuserinteraction方法

public void onuserinteraction() {
}

从代码可以了解

  1. 调用activity的onuserinteraction方法,action为down时会进去onuserinteraction方法,但是这个是空方法不做任何事情,可以忽略。

  2. 调用window的superdispatchtouchevent方法,返回true时事件分发处理结束,否则会调用activity的ontouchevent方法。

  3. 调用activity的ontouchevent方法,进入这个条件的方法是window的superdispatchtouchevent方法返回false。从上面的分析(二、不拦截处理任何事件)可以知道,所有子view的dispatchtouchevent、onintercepttouchevent、ontouchevent都返回false时会调动activity的ontouchevent方法,这个时候也是使window的superdispatchtouchevent方法返回false成立。

二、window的superdispatchtouchevent

activity的getwindow方法

public window getwindow() {
    return mwindow;
}

mwindow是如何赋值的?
是在activity的attach方法赋值的,其实mwindow是phonewindow。

activity的attach方法

final void attach(context context, activitythread athread,
        instrumentation instr, ibinder token, int ident,
        application application, intent intent, activityinfo info,
        charsequence title, activity parent, string id,
        nonconfigurationinstances lastnonconfigurationinstances,
        configuration config, string referrer, ivoiceinteractor voiceinteractor,
        window window, activityconfigcallback activityconfigcallback) {
    attachbasecontext(context);

    mfragments.attachhost(null /*parent*/);

    mwindow = new phonewindow(this, window, activityconfigcallback);
    mwindow.setwindowcontrollercallback(this);
    mwindow.setcallback(this);
    mwindow.setonwindowdismissedcallback(this);
    mwindow.getlayoutinflater().setprivatefactory(this);
    ...
}

phonewindow的superdispatchtouchevent方法

private decorview mdecor;

@override
public boolean superdispatchtouchevent(motionevent event) {
    return mdecor.superdispatchtouchevent(event);
}

devorview的superdispatchtouchevent

public boolean superdispatchtouchevent(motionevent event) {
    return super.dispatchtouchevent(event);
}

而mdecor是一个继承framelayout的decorview,就这样把事件分发到viewgroup上了。

三、viewgroup的dispatchtouchevent

3.1 viewgroup拦截事件的情况

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

这里分为2种情况会判断是否需要拦截,也就是当某一条件成立时,会执行onintercepttouchevent判断是否需要拦截事件。

  1. 当actionmasked == motionevent.action_down时。
  2. 当mfirsttouchtarget != null时。mfirsttouchtarget是成功处理事件的viewgroup的子view,也就是viewgroup的子view在以下情况返回true时,这个在log分析流程图轻易得到:

    2.1 dispatchtouchevent返回true

    2.2 如果子view是viewgroup时,onintercepttouchevent、ontouchevent返回true

另外还有一种情况是disallowintercept为true时,intercepted直接赋值false不进行拦截。flag_disallow_intercept是通过requestdisallowintercepttouchevent方法来设置的,用于在子view中设置,设置后viewgroup只能拦截down事件,无法拦截其他move、up、cancel事件。为什么viewgroup还能拦截down事件呢?因为viewgroup在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();
}

private void resettouchstate() {
    cleartouchtargets();
    resetcancelnextupflag(this);
    mgroupflags &= ~flag_disallow_intercept;
    mnestedscrollaxes = scroll_axis_none;
}

通过源码可以了解到,viewgroup拦截事件后,不再调用onintercepttouchevent,而是直接交给mfirsttouchtarget的ontouchevent处理,如果该ontouchevent不处理最终会交给activity的ontouchevent。

3.2 viewgroup不拦截事件的情况

viewgroup不拦截事件时,会遍历子view,使事件分发到子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 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;
    }
}
3.2.1 寻找可接收事件的子view

通过canviewreceivepointerevents判断子view是否能够接收到点击事件。必须符合2种情况,缺一不可:1、点击事件的坐标落在在子view的区域内;2、子view没有正在播放动画。满足条件后,调用dispatchtransformedtouchevent,其实也是调用子view的dispatchtouchevent。

private static boolean canviewreceivepointerevents(@nonnull view child) {
    return (child.mviewflags & visibility_mask) == visible
            || child.getanimation() != null;
}

protected boolean istransformedtouchpointinview(float x, float y, view child,
        pointf outlocalpoint) {
    final float[] point = gettemppoint();
    point[0] = x;
    point[1] = y;
    transformpointtoviewlocal(point, child);
    final boolean isinview = child.pointinview(point[0], point[1]);
    if (isinview && outlocalpoint != null) {
        outlocalpoint.set(point[0], point[1]);
    }
    return isinview;
}

private boolean dispatchtransformedtouchevent(motionevent event, boolean cancel,
        view child, int desiredpointeridbits) {
    final boolean handled;
    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;
    }

    ...

    // perform any necessary transformations and dispatch.
    if (child == null) {
        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());
        }

        handled = child.dispatchtouchevent(transformedevent);
    }

    // done.
    transformedevent.recycle();
    return handled;
}

当dispatchtransformedtouchevent返回true时,结束for循环遍历,赋值newtouchtarget,相当于发现了可以接收事件的view,不用再继续找了。

newtouchtarget = addtouchtarget(child, idbitstoassign);
alreadydispatchedtonewtouchtarget = true;
break;

在addtouchtarget方法赋值mfirsttouchtarget。

private touchtarget addtouchtarget(@nonnull view child, int pointeridbits) {
    final touchtarget target = touchtarget.obtain(child, pointeridbits);
    target.next = mfirsttouchtarget;
    mfirsttouchtarget = target;
    return target;
}
3.2.2 viewgroup自己处理事件

另一种情况是mfirsttouchtarget为空时,viewgroup自己处理事件,这里注意第三个参数为null,viewgroup的super.dispatchtouchevent将调用view的dispatchtouchevent。

if (mfirsttouchtarget == null) {
    // no touch targets so treat this as an ordinary view.
    handled = dispatchtransformedtouchevent(ev, canceled, null,
            touchtarget.all_pointer_ids);
}

3.3 view处理点击事件的过程

view的dispatchtouchevent是怎么处理事件的呢?

public boolean dispatchtouchevent(motionevent event) {
    boolean result = false;
    ...
    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;
        }
    }
    ...
    return result;
}
  1. 首先使用onfiltertoucheventforsecurity方法过滤不符合应用安全策略的触摸事件。

     public boolean onfiltertoucheventforsecurity(motionevent event) {
         //noinspection redundantifstatement
         if ((mviewflags & filter_touches_when_obscured) != 0
                 && (event.getflags() & motionevent.flag_window_is_obscured) != 0) {
             // window is obscured, drop this touch.
             return false;
         }
         return true;
     }
  2. montouchlistener != null判断是否设置了ontouchevent,设置了就执行montouchlistener.ontouch并返回true,不再执行ontouchevent。这里得出ontouchevent的优先级高于ontouchevent,便于使用setontouchlistener设置处理点击事件。

  3. 另一种情况是进入ontouchevent进行处理。

     public boolean ontouchevent(motionevent event) {
         final float x = event.getx();
         final float y = event.gety();
         final int viewflags = mviewflags;
         final int action = event.getaction();
    
         final boolean clickable = ((viewflags & clickable) == clickable
                 || (viewflags & long_clickable) == long_clickable)
                 || (viewflags & context_clickable) == context_clickable;
    
         if ((viewflags & enabled_mask) == disabled) {
             if (action == motionevent.action_up && (mprivateflags & pflag_pressed) != 0) {
                 setpressed(false);
             }
             mprivateflags3 &= ~pflag3_finger_down;
             // a disabled view that is clickable still consumes the touch
             // events, it just doesn't respond to them.
             return clickable;
         }
         ...
     }

当view不可用时,依然会处理事件,只是看起来不可用。

接着执行mtouchdelegate.ontouchevent

if (mtouchdelegate != null) {
    if (mtouchdelegate.ontouchevent(event)) {
        return true;
    }
}

下面看看up事件是怎么处理的

/**
 * <p>indicates this view can display a tooltip on hover or long press.</p>
 * {@hide}
 */
static final int tooltip = 0x40000000;

if (clickable || (viewflags & tooltip) == tooltip) {
    switch (action) {
        case motionevent.action_up:
            mprivateflags3 &= ~pflag3_finger_down;
            if ((viewflags & tooltip) == tooltip) {
                handletooltipup();
            }
            if (!clickable) {
                removetapcallback();
                removelongpresscallback();
                mincontextbuttonpress = false;
                mhasperformedlongpress = false;
                mignorenextupevent = false;
                break;
            }
            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)) {
                            performclickinternal();
                        }
                    }
                }

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

    return true;
}

从上面代码可以了解,clickable、tooltip(长按)有一个为true时,就会消耗事件,使ontouchevent返回true。其中performclick内部调用了performclick方法。

public boolean performclick() {
    // we still need to call this method to handle the cases where performclick() was called
    // externally, instead of through performclickinternal()
    notifyautofillmanageronclick();

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

    notifyenterorexitforautofillifneeded(true);

    return result;
}

如果view设置了onclicklistener,那performclick会调用内部的onclick方法。

public void setonclicklistener(@nullable onclicklistener l) {
    if (!isclickable()) {
        setclickable(true);
    }
    getlistenerinfo().monclicklistener = l;
}

public void setonlongclicklistener(@nullable onlongclicklistener l) {
    if (!islongclickable()) {
        setlongclickable(true);
    }
    getlistenerinfo().monlongclicklistener = l;
}

通过setonclicklistener设置clickable,通过setonlongclicklistener设置long_clickable长按事件。设置后使得ontouchevent返回true。到这里我们已经分析完成点击事件的分发过程了。

本文地址:

本文参考以下内容:

1、《android开发艺术探索》