Para expandir el área táctil genéricamente con muy pocas restricciones, use el siguiente código.
Le permite expandir el área táctil de lo dado viewdentro de la ancestorvista dada por lo dado expansionen píxeles. Puede elegir cualquier antepasado siempre que la vista dada esté en el árbol de diseño de antepasados.
public static void expandTouchArea(final View view, final ViewGroup ancestor, final int expansion) {
ancestor.post(new Runnable() {
public void run() {
Rect bounds = getRelativeBounds(view, ancestor);
Rect expandedBounds = expand(bounds, expansion);
ancestor.setTouchDelegate(new TouchDelegate(expandedBounds, view));
}
private Rect getRelativeBounds(View view, ViewGroup ancestor) {
Point relativeLocation = getRelativeLocation(view, ancestor);
return new Rect(relativeLocation.x, relativeLocation.y,
relativeLocation.x + view.getWidth(),
relativeLocation.y + view.getHeight());
}
private Point getRelativeLocation(View view, ViewGroup ancestor) {
Point absoluteAncestorLocation = getAbsoluteLocation(ancestor);
Point absoluteViewLocation = getAbsoluteLocation(view);
return new Point(absoluteViewLocation.x - absoluteAncestorLocation.x,
absoluteViewLocation.y - absoluteAncestorLocation.y);
}
private Point getAbsoluteLocation(View view) {
int[] absoluteLocation = new int[2];
view.getLocationOnScreen(absoluteLocation);
return new Point(absoluteLocation[0], absoluteLocation[1]);
}
private Rect expand(Rect rect, int by) {
Rect expandedRect = new Rect(rect);
expandedRect.left -= by;
expandedRect.top -= by;
expandedRect.right += by;
expandedRect.bottom += by;
return expandedRect;
}
});
}
Restricciones que aplican:
- El área táctil no puede exceder los límites del ancestro de la vista, ya que el ancestro debe poder capturar el evento táctil para reenviarlo a la vista.
- Solo uno
TouchDelegatese puede establecer en a ViewGroup. Si desea trabajar con múltiples delegados táctiles, elija diferentes antepasados o use un delegado táctil de composición como se explica en Cómo usar múltiples TouchDelegate .