बहुत कम प्रतिबंधों के साथ उदारता से स्पर्श क्षेत्र का विस्तार करने के लिए निम्नलिखित कोड का उपयोग करें।
यह आपको पिक्सेल में दिए viewगए ancestorदृश्य के भीतर दिए गए स्पर्श क्षेत्र का विस्तार करने देता है expansion। जब तक दिया गया दृश्य पूर्वजों के लेआउट ट्री में है, तब तक आप किसी भी पूर्वज को चुन सकते हैं।
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;
}
});
}
लागू होने वाले प्रतिबंध:
- स्पर्श क्षेत्र दृश्य के पूर्वज की सीमा से अधिक नहीं हो सकता है क्योंकि पूर्वज को स्पर्श घटना को देखने के लिए अग्रेषित करने में सक्षम होना चाहिए।
- केवल एक
TouchDelegateको सेट किया जा सकता है ViewGroup। यदि आप कई टच डेलिगेट्स के साथ काम करना चाहते हैं, तो विभिन्न पूर्वजों का चयन करें या कंपोज़िंग टच डेलिगेट का उपयोग करें जैसे कि कैसे कई टचडेलगेट का उपयोग करें ।