Android事件分发之ACTION_CANCEL机制及作用

如果要查看ACTION_MOVE与ACTION_UP的事件传递机制,查看Android事件分发之ACTION_MOVE与ACTION_UP的传递机制

ACTION_CANCEL产生场景

在阅读ViewGroup事件分发相关源码过程中,有时候会见到ACTION_CANCEL这一事件。那么这一事件是如何产生的呢?按照网上的说法,当手指从当前view移出后,当前view就会收到ACTION_CANCEL这一事件,这一定是正确的吗?下面我们来看两个例子:

例子1:


import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent

class CustomViewGroup @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
   
   

    var hasInterceptMoveEvent = false
    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
   
   
        // Log.d("TAG", "${ev?.action}:CustomViewGroup onInterceptTouchEvent")
        if (!hasInterceptMoveEvent && ev?.action == MotionEvent.ACTION_MOVE) {
   
   
            hasInterceptMoveEvent = true
            return true
        }
        return false
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
   
   
        Log.d("TAG", "${
     
     getAction(ev?.action)}:CustomViewGroup dispatchTouchEvent")
        return super.dispatchTouchEvent(ev)
        
    }


}

我们自定义一个ViewGroup,覆盖它的onInterceptTouchEvent方法和dispatchTouchEvent方法。在onInterceptTouchEvent方法中我们只拦截了一次MotionEvent.ACTION_MOVE事件。hasInterceptMoveEvent用于控制只拦截一次。而在dispatchTouchEvent方法中,我们打印出当前ViewGroup处理的事件。看下getAction方法定义:

fun getAction(action: Int?): String {
    return when (action) {
        MotionEvent.ACTION_DOWN -> "MotionEvent.ACTION_DOWN"
        MotionEvent.ACTION_MOVE -> "MotionEvent.ACTION_MOVE"
        MotionEvent.ACTION_UP -> "MotionEvent.ACTION_UP"
        MotionEvent.ACTION_CANCEL -> "MotionEvent.ACTION_CANCEL"
        else -> "OTHER"
    }
}

其实就是根据Action对应的Int值转化为字符串,让我们的Log更加直观。

而在ViewGroup内部,我们放置了一个自定义Button。代码如下:


class CusButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : Button(context, attrs, defStyleAttr) {
   
   
    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
   
   
        Log.d("TAG", "${
     
     getAction(event?.action)}:CusButton dispatchTouchEvent")
        return true
    }
}

这个自定义Button只是将当前dispatchTouchEvent方法收到的事件打印出来。

在这里插入图片描述
现在我们进行如下操作:

手指按住button,然后移动,移出button外,然后松开。我们看下打印出的Log:

04-23 15:13:48.553 22928-22928/com.lee.myapplication D/TAG: MotionEvent.ACTION_DOWN:CustomViewGroup dispat

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值