I have implemented GestureDetector
in my Activity
. Right now I can grab all events from whole screen like onSingleTapConfirmed
, onDoubleTap
, onLongPress
...
Is it possible to detect, which View
from my custom layout was pressed ?
In Android you have the platform source code, so I would recommend to see how the core ViewGroups are implemented and learn from them.
Let's examine the source for ViewGroup
available here. Look for the function dispatchTouchEvent()
. It does pretty much what you're looking to do.
To figure out which view was actually tapped, it iterates over all the subviews, asks for the hitrect for each view and checks if it's relevant. Code:
for (int i = count - 1; i >= 0; i--) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null) {
child.getHitRect(frame);
if (frame.contains(scrolledXInt, scrolledYInt)) {
I can only suggest you do something similar.
I guess that you won't want to do this manual iteration (or recursion since you probably want to go into views within views) because, let's face it, it's pretty disgusting. In this case, maybe you can let the regular mechanism do its charm (let the event flow into the subviews as it normally would). Then set event handlers on the specific views you want to handle, and let your handler be called and notify you somehow which view was tapped.
Another interesting thing to keep in mind is that custom layouts may implement static transformations for their subviews with ViewGroup.setStaticTransformationsEnabled()
. I used these transformations when I've implemented a 3D view carousel. When this is the case, I'm pretty sure what you want to do is impossible. The subviews don't really know where they are because the static transformations draw them somewhere else on screen. In this case, you are under the grace of the custom layout to dispatch events to its subviews correctly for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With