Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

If i know coordinates(X,Y) pixel (by OnTouchEvent method and getX(),getY) how i can find element ex. button or text etc.... by use X,Y

like image 991
iiinatt Avatar asked Jun 09 '12 08:06

iiinatt


People also ask

How do you find X and Y coordinates on Android?

getX() + ":" + (int)button1. getY(), Toast. LENGTH_LONG). show();

Which javascript function would you use to get the element at a given coordinates?

The elementFromPoint() method, available on the Document object, returns the topmost Element at the specified coordinates (relative to the viewport).


2 Answers

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

like image 179
Fuzzical Logic Avatar answered Oct 11 '22 20:10

Fuzzical Logic


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;
}
like image 35
Luke Avatar answered Oct 11 '22 20:10

Luke