Android View TouchDelegate

Android View TouchDelegate

  • TouchDelegate 用于扩大某个 View 的触摸区域,将父容器指定的矩形区域内的触摸事件转发给目标 View 处理,当用户点击这块指定区域时,事件会被转发到目标 View 的 onTouchEvent 方法中处理,当然也可以通过 TouchDelegate 缩小子 View 的触摸区域
  • TouchDelegate 必须设置在目标视 View 的父容器上,而非 View 本身,一个父容器只能设置一个 TouchDelegate
  • 扩展区域的坐标是相对于父容器的,需确保计算后的区域不超出父容器边界
  • 其他方案:设置 Padding、自定义 onTouchEvent 逻辑
kotlin 复制代码
fun View.expandTouchRect(expandSize: Int) {
    val parentView = parent as View
    parentView.post {
        val rect = Rect()
        //获取目标 View 在其父视图中的当前原始边界
        getHitRect(rect)
        //扩展区域边界
        rect.left -= expandSize
        rect.top -= expandSize
        rect.right += expandSize
        rect.bottom += expandSize
        //扩展区域边界
        //rect.inset(-expandSize, -expandSize)
        //确保扩展后的矩形不会超过父视图的边界
        val parentRect = Rect()
        parentView.getHitRect(parentRect)
        val result = rect.intersect(parentRect)
        //在父容器中设置委托(代理)区域
        parentView.touchDelegate = TouchDelegate(rect, this)
    }
}
fun View.resetTouchRect() {
    val parentView = parent as View
    //通过设置空的 Rect 来恢复视图的原始触摸区域
    parentView.touchDelegate = TouchDelegate(Rect(), this)
}
相关推荐
火柴就是我10 小时前
让我们实现一个更好看的内部阴影按钮
android·flutter
砖厂小工16 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心17 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心17 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker19 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴20 小时前
Android17 为什么重写 MessageQueue
android
阿巴斯甜2 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95272 天前
Andorid Google 登录接入文档
android
黄林晴2 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack