How to pass click events to Android child views

written

When dealing with child views in Android, nesting views with touch events can wipe out basic onClick behavior. This can turn a happy developer into a “punch stranger in the face” developer in no time flat. To return the rabbit developer back to normal, I scraped together the following snippet.

View innerMostChild(MotionEvent event) {

return innerMostChild(event, this, 0);

}

View innerMostChild(MotionEvent event, ViewGroup view, int nesting) {

View result = null;

final float x = event.getX();

final float y = event.getY();

for (int i = view.getChildCount() - 1; i >= 0; i–) {

View child = view.getChildAt(i);

// check if click is within bounds

if (x >= child.getLeft() && x < child.getRight() && y >= child.getTop() && y < child.getBottom()) {

if (logv) Log.v(TAG, String.format(“>%” + (nesting == 0 ? ”” : nesting * 2) + ”s child: %s”, ””, child.getClass().getSimpleName()));

            if (child instanceof ViewGroup) {

            result = innerMostChild(event, (ViewGroup) child, nesting+1);

            } else {

        result = child;

            }

}

}

return result;

}

Then make the call to your innerMostChild within your GestureDetector:

 

@Override

public boolean onSingleTapUp(MotionEvent e) {

View child = innerMostChild(e);

if (child != null) {

child.performClick();

return true;

}

return false;

}

This isn’t quite production ready code, so I’ll leave refactoring to whoever wants to use it.

I might post the whole file if some one asks nicely.

PS. Sorry strange, I couldn’t help it.