Android View增加可点击区域

476 阅读1分钟

通过TouchDelegate,可以指定View外部的触摸区域交给View处理。

/**
 * 扩大view的点击范围
 *
 * @param view
 * @param expandLeft
 * @param expandTop
 * @param expandRight
 * @param expandBottom
 */
public static void expandClickArea(@NonNull final View view,
                                   final int expandLeft,
                                   final int expandTop,
                                   final int expandRight,
                                   final int expandBottom) {
    final View parentView = (View) view.getParent();
    if (parentView != null) {
        parentView.post(() -> {
            final Rect rect = new Rect();
            view.getHitRect(rect);
            rect.left -= expandLeft;
            rect.top -= expandTop;
            rect.right += expandRight;
            rect.bottom += expandBottom;
            parentView.setTouchDelegate(new TouchDelegate(rect, view));
        });
    }
}