[英]How to find element in View by coordinates x,y Android
如果我知道坐標(X,Y)像素(通過 OnTouchEvent 方法和 getX(),getY)我如何找到元素 ex。 按鈕或文本等.... 使用X,Y
您可以使用每個子視圖的getHitRect(outRect)
並檢查該點是否在結果矩形中。 這是一個快速示例。
for(int _numChildren = getChildCount(); --_numChildren)
{
View _child = getChildAt(_numChildren);
Rect _bounds = new Rect();
_child.getHitRect(_bounds);
if (_bounds.contains(x, y)
// In View = true!!!
}
希望這可以幫助,
模糊邏輯
一個稍微更完整的答案,它接受任何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;
}
與https://stackoverflow.com/a/10959466/2557258相同的解決方案,但在 kotlin 中:
fun ViewGroup.getViewByCoordinates(x: Float, y: Float) : View? {
(childCount - 1 downTo 0)
.map { this.getChildAt(it) }
.forEach {
val bounds = Rect()
it.getHitRect(bounds)
if (bounds.contains(x.toInt(), y.toInt())) {
return it
}
}
return null
}
修改@Luke 提供的答案。 不同之處在於使用getHitRect
而不是getLocationOnScreen
。 我發現getLocationOnScreen
對選擇的視圖不准確。 還將代碼轉換為 Kotlin 並使其成為ViewGroup
的擴展:
/**
* Find the [View] at the provided [x] and [y] coordinates within the [ViewGroup].
*/
fun ViewGroup.findViewAt(x: Int, y: Int): View? {
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child is ViewGroup) {
val foundView = child.findViewAt(x, y)
if (foundView != null && foundView.isShown) {
return foundView
}
} else {
val rect = Rect()
child.getHitRect(rect)
if (rect.contains(x, y)) {
return child
}
}
}
return null
}
Android 使用 dispatchKeyEvent/dispatchTouchEvent 找到正確的視圖來處理按鍵/觸摸事件,這是一個復雜的過程。 因為可能有很多視圖覆蓋 (x, y) 點。
但是,如果您只想找到覆蓋 (x, y) 點的最上方視圖,這很簡單。
1 使用 getLocationOnScreen() 獲取絕對位置。
2 使用 getWidth()、getHeight() 判斷視圖是否覆蓋 (x, y) 點。
3 計算整個視圖樹中的視圖級別。 (遞歸調用 getParent() 或使用某種搜索方法)
4 找到既覆蓋點又具有最大層的視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.