Per espandere genericamente l'area di tocco con poche restrizioni, utilizzare il seguente codice.
Consente di espandere l'area di tocco del dato view
all'interno della vista ancestor
in base allo expansion
indicato in pixel. È possibile scegliere qualsiasi antenato purché la vista data si trovi nell'albero di layout degli antenati.
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);
// LOG.debug("Expanding touch area of {} within {} from {} by {}px to {}", view, ancestor, bounds, expansion, expandedBounds);
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;
}
});
}
restrizioni che si applicano:
- L'area tocco non può superare i limiti di antenato della vista in quanto l'antenato deve essere in grado di catturare l'evento di tocco per inoltrare alla vista.
- Solo uno
TouchDelegate
può essere impostato su un ViewGroup
. Se vuoi lavorare con delegati a più contatti, scegli antenati diversi o usa un delegato per il tocco di composizione come spiegato in How To Use Multiple TouchDelegate.
fonte
2017-05-18 15:25:16
Ecco un altro post utile su come utilizzare TouchDelegate: http://groups.google.com/group/android-developers/browse_thread/thread/178af525ab84b371 –
Buona esercitazione: [Ampie aree estendibili] (http: // android.cyrilmottier.com/?p=574) –