2012-06-09 23 views

Respuesta

15

Puede usar getHitRect(outRect) de cada niño Ver y comprobar si el punto está en el rectángulo resultante. Aquí hay una muestra rápida.

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

Espero que esto ayude,

FuzzicalLogic

+1

He probado y funciona. –

+0

Funciona bien, pero parece que el elemento secundario puede ser nulo, por lo que se necesita una verificación para evitar la NullPointerException. –

+0

funciona perfecto. –

0

uso androide dispatchKeyEvent/dispatchTouchEvent a encontrar la visión adecuada para manejar evento clave/táctil, que es un procedimiento complejo. Como puede haber muchas vistas, cubra el punto (x, y).

Pero es simple si solo desea encontrar la vista más superior que cubra el punto (x, y).

1 Use getLocationOnScreen() para obtener la posición absoulte.

2 Use getWidth(), getHeight() para averiguar si la vista cubre el punto (x, y).

3 Categule el nivel de vista en el árbol de vista completa. (Llame a getParent() recursivamente o use algún método de búsqueda)

4 Busque la vista que cubra el punto y tenga el nivel más alto.

4

Una respuesta un poco más completa que acepta cualquier ViewGroup y buscará recursivamente la vista en la x, y dada.

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

La misma solución que https://stackoverflow.com/a/10959466/2557258 pero en 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 
} 
Cuestiones relacionadas