Để mở rộng vùng cảm ứng một cách chung chung với các hạn chế khá ít, hãy sử dụng mã sau đây.
Tính năng này cho phép bạn mở rộng vùng cảm ứng của view
nhất định trong chế độ xem ancestor
nhất định theo expansion
theo pixel. Bạn có thể chọn bất kỳ tổ tiên nào miễn là khung nhìn nhất định nằm trong cây bố trí tổ tiên.
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;
}
});
}
hạn chế áp dụng:
- Khu vực cảm ứng không thể vượt quá giới hạn của tổ tiên của xem kể từ khi tổ tiên phải có khả năng nắm bắt những sự kiện liên lạc để chuyển tiếp nó để xem.
- Chỉ một
TouchDelegate
mới có thể được đặt thành ViewGroup
. Nếu bạn muốn làm việc với nhiều đại biểu cảm ứng, hãy chọn tổ tiên khác nhau hoặc sử dụng một đại biểu cảm ứng sáng tác như được giải thích trong How To Use Multiple TouchDelegate.
Nguồn
2017-05-18 15:25:16
Đây là bài đăng bổ sung về cách sử dụng TouchDelegate: http://groups.google.com/group/android-developers/browse_thread/thread/178af525ab84b371 –
Hướng dẫn hay: [Vùng có thể mở rộng được mở rộng] (http: // android.cyrilmottier.com/?p=574) –