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)
}
相关推荐
大熊的瓜地6 小时前
Android automotive 框架
android·android car
私人珍藏库7 小时前
[Android] Alarm Clock Pro 11.1.0一款经典简约个性的时钟
android·时钟
消失的旧时光-19439 小时前
ScheduledExecutorService
android·java·开发语言
小糖学代码9 小时前
MySQL:14.mysql connect
android·数据库·mysql·adb
怪兽201411 小时前
请谈谈什么是同步屏障?
android·面试
帅锅锅00712 小时前
SeLinux 全面详解
android·linux
只想搞钱的肥仔12 小时前
Android thermal (5)_cooling device(下)
android
某空m12 小时前
【Android】BottomNavigationView实现底部导航栏
android·java
撩得Android一次心动13 小时前
Android 四大组件桥梁 —— Intent (意图) 详解
android
用户20187928316714 小时前
MVP架构模式:餐厅点餐的有趣故事
android