扩大点击区域

Android中常用扩大点击区域的方式是为View添加padding, 并重新计算View的尺寸. Android中提供了另一种方式: TouchDelegate

TouchDelegate

Android TouchDelegate is a powerful tool that helps developers create a custom touch region for a View. This allows developers to extend the area of the View that responds to touch events. For example, if a View is small, developers can use TouchDelegate to increase the area that responds to touch events. This makes it easier to interact with the View and makes the user experience more seamless. The TouchDelegate class also helps developers create custom touch feedback, such as a ripple effect, when the user interacts with a View. This can make the user experience more intuitive and engaging.

用法

((View) view.getParent()).post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right += right;
                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);
                if (view.getParent() instanceof View) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });

原理

  1. 为什么可以扩大区域? 当View中有点击事件时首先交给TouchDelegate判断,是否在它扩大后的Rect范围内,在范围内把点击的坐标映射到target范围内后,按照正常的事件分发处理。
  2. 为什么需要写在父类中? 如果在子View中写扩大子View的范围,扩大的范围甚至都不在子View的范围,怎么实现扩大呢。
  3. TouchDelegate中滑动判断?
  4. 怎么避免被代理的子View重复处理事件? 先判断TouchDelegate是否消费,若消费事件分发完成,不消费按照正常的流程。

需要注意的是一个父View中只能为一个子View设置TouchDelegate= =|||