You need to enable JavaScript to run this app. 跳转其他Fragment时OnTouchListener无法触发ACTION_UP事件该如何解决
优惠活动
大模型
产品
解决方案
定价
更多

跳转其他Fragment时OnTouchListener无法触发ACTION_UP事件该如何解决

问题修复方案

根因说明

  • 跳转Fragment时原按钮所在的View会从View树中移除,系统会终止原有触摸事件流,下发MotionEvent.ACTION_CANCEL事件而非ACTION_UP,原有代码未处理该事件,因此释放逻辑无法触发。
  • 多点触控场景下直接读取event.action无法正确解析事件类型,需用event.actionMasked获取归一化的事件标识。

修复代码

view.findViewById<Button>(R.id.button).setOnTouchListener { _, event ->
    when (event.actionMasked) {
        MotionEvent.ACTION_DOWN -> {
            doAction(true)
            true
        }
        MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
            doAction(false)
            true
        }
        else -> false
    }
}

补充说明

该修复同时覆盖了其他触摸异常终止的场景:比如按钮嵌套在滑动布局中,滑动时父布局拦截触摸事件,也会触发ACTION_CANCEL,保证释放逻辑一定会执行。

内容的提问来源于stack exchange,提问作者Markus Tonsaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 13:36:03