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

Android中ACTION_CANCEL的触发机制与滑出子view的情况

程序员文章站 2023-12-23 10:06:10
目录action_cancel的触发时机2,action_down初始化操作3,在子view处理事件的过程中被从父view中移除时4,子view被设置了pflag_cancel_next_up_eve...

看完本文你将了解:

  • action_cancel的触发时机
  • 滑出子view区域会发生什么?为什么不响应onclick()事件

首先看一下官方的解释:

/**
 * constant for {@link #getactionmasked}: the current gesture has been aborted.
 * you will not receive any more points in it.  you should treat this as
 * an up event, but not perform any action that you normally would.
 */
public static final int action_cancel           = 3;

说人话就是:当前的手势被中止了,你不会再收到任何事件了,你可以把它当做一个action_up事件,但是不要执行正常情况下的逻辑。

action_cancel的触发时机

有四种情况会触发action_cancel:

  • 在子view处理事件的过程中,父view对事件拦截
  • action_down初始化操作
  • 在子view处理事件的过程中被从父view中移除时
  • 子view被设置了pflag_cancel_next_up_event标记时

1,父view拦截事件

首先要了解viewgroup什么情况下会拦截事件,look the fuck resource code:

/**
 * {@inheritdoc}
 */
@override
public boolean dispatchtouchevent(motionevent ev) {
	...

    boolean handled = false;
    if (onfiltertoucheventforsecurity(ev)) {
        final int action = ev.getaction();
        final int actionmasked = action & motionevent.action_mask;
		...
        // 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;
        }
        ...
    }
    ...
}

有两个条件

  • motionevent.action_down事件或者mfirsttouchtarget非空也就是有子view在处理事件
  • 子view没有做拦截,也就是没有调用viewparent#requestdisallowintercepttouchevent(true)

如果满足上面的两个条件才会执行onintercepttouchevent(ev)
如果viewgroup拦截了事件,则intercepted变量为true,接着往下看:

@override
public boolean dispatchtouchevent(motionevent ev) {
    
    boolean handled = false;
    if (onfiltertoucheventforsecurity(ev)) {
        ...

        // check for interception.
        final boolean intercepted;
        if (actionmasked == motionevent.action_down
                || mfirsttouchtarget != null) {
            final boolean disallowintercept = (mgroupflags & flag_disallow_intercept) != 0;
            if (!disallowintercept) {
                // 当mfirsttouchtarget != null,也就是子view处理了事件
                // 此时如果父viewgroup拦截了事件,intercepted==true
                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;
        }

        ...

        // dispatch to touch targets.
        if (mfirsttouchtarget == null) {
            ...
        } 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) {
                    ...
                } else {
                    // 判断一:此时cancelchild == true
                    final boolean cancelchild = resetcancelnextupflag(target.child)
                            || intercepted;

					// 判断二:给child发送cancel事件
                    if (dispatchtransformedtouchevent(ev, cancelchild,
                            target.child, target.pointeridbits)) {
                        handled = true;
                    }
                    ...
                }
                ...
            }
        }
        ...
    }
    ...
    return handled;
}

以上判断一处cancelchild为true,然后进入判断二中一看究竟:

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设置成action_cancel
        event.setaction(motionevent.action_cancel);
        if (child == null) {
            ...
        } else {
            // 分发给child
            handled = child.dispatchtouchevent(event);
        }
        event.setaction(oldaction);
        return handled;
    }
    ...
}

当参数cancel为ture时会将event设置为motionevent.action_cancel,然后分发给child。

2,action_down初始化操作

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.
            // 取消并清除所有的touch目标
            cancelandcleartouchtargets(ev);
            resettouchstate();
    	}
    	...
    }
    ...
}

系统可能会由于app切换、anr等原因丢失了up,cancel事件。

因此需要在action_down时丢弃掉所有前面的状态,具体代码如下:

private void cancelandcleartouchtargets(motionevent event) {
    if (mfirsttouchtarget != null) {
        boolean syntheticevent = false;
        if (event == null) {
            final long now = systemclock.uptimemillis();
            event = motionevent.obtain(now, now,
                    motionevent.action_cancel, 0.0f, 0.0f, 0);
            event.setsource(inputdevice.source_touchscreen);
            syntheticevent = true;
        }

        for (touchtarget target = mfirsttouchtarget; target != null; target = target.next) {
            resetcancelnextupflag(target.child);
            // 分发事件同情况一
            dispatchtransformedtouchevent(event, true, target.child, target.pointeridbits);
        }
        ...
    }
}

ps:在dispatchdetachedfromwindow()中也会调用cancelandcleartouchtargets()

3,在子view处理事件的过程中被从父view中移除时

public void removeview(view view) {
    if (removeviewinternal(view)) {
        requestlayout();
        invalidate(true);
    }
}

private boolean removeviewinternal(view view) {
    final int index = indexofchild(view);
    if (index >= 0) {
        removeviewinternal(index, view);
        return true;
    }
    return false;
}

private void removeviewinternal(int index, view view) {

    ...
    canceltouchtarget(view);
	...
}

private void canceltouchtarget(view view) {
    touchtarget predecessor = null;
    touchtarget target = mfirsttouchtarget;
    while (target != null) {
        final touchtarget next = target.next;
        if (target.child == view) {
            ...
            // 创建action_cancel事件
            motionevent event = motionevent.obtain(now, now,
                    motionevent.action_cancel, 0.0f, 0.0f, 0);
            event.setsource(inputdevice.source_touchscreen);
            分发给目标view
            view.dispatchtouchevent(event);
            event.recycle();
            return;
        }
        predecessor = target;
        target = next;
    }
}

4,子view被设置了pflag_cancel_next_up_event标记时

在情况一种的两个判断处:

// 判断一:此时cancelchild == true
final boolean cancelchild = resetcancelnextupflag(target.child)
|| intercepted;

// 判断二:给child发送cancel事件
if (dispatchtransformedtouchevent(ev, cancelchild,
    target.child, target.pointeridbits)) {
    handled = true;
}

resetcancelnextupflag(target.child) 为true时同样也会导致cancel,查看代码:

/**
 * indicates whether the view is temporarily detached.
 *
 * @hide
 */
static final int pflag_cancel_next_up_event        = 0x04000000;

private static boolean resetcancelnextupflag(view view) {
    if ((view.mprivateflags & pflag_cancel_next_up_event) != 0) {
        view.mprivateflags &= ~pflag_cancel_next_up_event;
        return true;
    }
    return false;
}

根据注释大概意思是,该view暂时detached,detached是什么意思?就是和attached相反的那个,具体什么时候打了这个标记,我觉得没必要深究。

以上四种情况最重要的就是第一种,后面的只需了解即可。

滑出子view区域会发生什么?

了解了什么情况下会触发action_cancel,那么针对问题:滑出子view区域会触发action_cancel吗?这个问题就很明确了:不会。

实践是检验真理的唯一标准,代码撸起来:

public class mybutton extends androidx.appcompat.widget.appcompatbutton {

	@override
    public boolean ontouchevent(motionevent event) {
        switch (event.getaction()) {
            case motionevent.action_down:
                logutil.d("action_down");
                break;
            case motionevent.action_move:
                logutil.d("action_move");
                break;
            case motionevent.action_up:
                logutil.d("action_up");
                break;
            case motionevent.action_cancel:
                logutil.d("action_cancel");
                break;
        }
        return super.ontouchevent(event);
    }
}

一波操作以后日志如下:

(mybutton.java:32) -->action_down
(mybutton.java:36) -->action_move
(mybutton.java:36) -->action_move
(mybutton.java:36) -->action_move
(mybutton.java:36) -->action_move
(mybutton.java:36) -->action_move
(mybutton.java:39) -->action_up

滑出view后依然可以收到action_moveaction_up事件。

为什么有人会认为滑出view后会收到action_cancel呢?

我想是因为滑出view后,view的onclick()不会触发了,所以有人就以为是触发了action_cancel

那么为什么滑出view后不会触发onclick呢?再来看看view的源码:

在view的ontouchevent()中:

case motionevent.action_move:
    // be lenient about moving outside of buttons
	// 判断是否超出view的边界
    if (!pointinview(x, y, mtouchslop)) {
        // outside button
        if ((mprivateflags & pressed) != 0) {
            // 这里改变状态为 not pressed
            // need to switch from pressed to not pressed
            mprivateflags &= ~pressed;
        }
    }
    break;
    
case motionevent.action_up:
    boolean prepressed = (mprivateflags & pflag_prepressed) != 0;
    // 可以看到当move出view范围后,这里走不进去了
    if ((mprivateflags & pflag_pressed) != 0 || prepressed) {
        ...
        performclick();
        ...
    }
    mignorenextupevent = false;
    break;

1,在action_move中会判断事件的位置是否超出view的边界,如果超出边界则将mprivateflags置为not pressed状态。
2,在action_up中判断只有当mprivateflags包含pressed状态时才会执行performclick()等。
因此滑出view后不会执行onclick()

结论:

  • 滑出view范围后,如果父view没有拦截事件,则会继续受到action_moveaction_up等事件。
  • 一旦滑出view范围,view会被移除pressed标记,这个是不可逆的,然后在action_up中不会执行performclick()等逻辑。

到此这篇关于android中action_cancel的触发机制与滑出子view的情况的文章就介绍到这了,更多相关android action_cancel内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: