2012-06-09 21 views

回答

15

您可以使用每個子View的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

+1

我試着和它的作品。 –

+0

工程很好,但似乎孩子可以爲空,所以需要檢查以防止NullPointerException。 –

+0

它工作完美。 –

0

的Android使用dispatchKeyEvent/dispatchTouchEvent找到處理鍵/觸摸事件的右視圖,它是一個複雜的過程。由於可能有許多視圖覆蓋了(x,y)點。

但是,如果您只想找到涵蓋(x,y)點的最上面的視圖,這很簡單。

1使用getLocationOnScreen()獲取絕對位置。

2使用getWidth(),getHeight()來判斷視圖是否覆蓋(x,y)點。

3在整個視圖樹中調整視圖的級別。 (遞歸地調用getParent()或使用一些搜索方法)

4找到既涵蓋了點又具有最大級別的視圖。

4

稍微更完整的答案,接受任何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; 
} 
1

同樣的解決方案爲https://stackoverflow.com/a/10959466/2557258但在科特林:

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 
}