如何在坐标x,y Android中查看元素

如果我知道坐标(X,Y)像素(通过OnTouchEvent方法和getX(),getY)我怎么能find元素前。 按钮或文本等…通过使用X,Y

您可以使用每个子视图的getHitRect(outRect) ,并检查该点是否在生成的Rectangle中。 这是一个快速示例。

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

希望这可以帮助,

FuzzicalLogic

一个稍微更完整的答案,接受任何ViewGroup ,并递归搜索给定的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; } 

Android使用dispatchKeyEvent / dispatchTouchEvent来查找正确的视图来处理按键/触摸事件,这是一个复杂的过程。 由于可能有许多观点涵盖(x,y)点。

但是,如果您只想find覆盖(x,y)点的最上面的视图,这很简单。

1使用getLocationOnScreen()来获得绝对的位置。

2使用getWidth(),getHeight()来确定视图是否覆盖(x,y)点。

3在整个视图树中查看视图的级别。 (递归调用getParent()或使用某种搜索方法)

4发现既涵盖重点又具有最高水平的观点。

与https://stackoverflow.com/a/10959466/2557258相同的解决方案,但在kotlin中:

 fun getViewByCoordinates(viewGroup: ViewGroup, x: Float, y: Float) : View? { (0 until viewGroup.childCount) .map { viewGroup.getChildAt(it) } .forEach { val bounds = Rect() it.getHitRect(bounds) if (bounds.contains(x.toInt(), y.toInt())) { return it } } return null }