How to find element in View by coordinates x,y Android

A slightly more complete answer that accepts any ViewGroup and will recursively search for the view at the given x,y.

private View findViewAt(ViewGroup viewGroup, int x, int y) {
    for(int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        if (child instanceof ViewGroup) {
            View foundView = findViewAt((ViewGroup) child, x, y);
            if (foundView != null && foundView.isShown()) {
                return foundView;
            }
        } else {
            int[] location = new int[2];
            child.getLocationOnScreen(location);
            Rect rect = new Rect(location[0], location[1], location[0] + child.getWidth(), location[1] + child.getHeight());
            if (rect.contains(x, y)) {
                return child;
            }
        }
    }

    return null;
}

You could use getHitRect(outRect) of each child View and check if the point is in the resulting Rectangle. Here is a quick sample.

for(int _numChildren = getChildCount(); --_numChildren)
{
    View _child = getChildAt(_numChildren);
    Rect _bounds = new Rect();
    _child.getHitRect(_bounds);
    if (_bounds.contains(x, y)
        // In View = true!!!
}

Hope this helps,

FuzzicalLogic

Tags:

Android