如何从android中的事件坐标获取视图?

hta*_*oya 25 events android view

我想用我的父视图拦截触摸事件onInterceptTouchEvent (MotionEvent ev).

从那里我想知道点击了哪个视图以便做其他事情,有没有办法知道从收到的动议事件中点击了哪个视图?

hta*_*oya 80

对于任何想知道我做了什么的人来说......我做不到.我做了一个解决方法,只知道我的特定视图组件是否被点击,所以我只能以此结束:

   if(isPointInsideView(ev.getRawX(), ev.getRawY(), myViewComponent)){
    doSomething()
   }
Run Code Online (Sandbox Code Playgroud)

和方法:

/**
 * Determines if given points are inside view
 * @param x - x coordinate of point
 * @param y - y coordinate of point
 * @param view - view object to compare
 * @return true if the points are within view bounds, false otherwise
 */
public static boolean isPointInsideView(float x, float y, View view){
    int location[] = new int[2];
    view.getLocationOnScreen(location);
    int viewX = location[0];
    int viewY = location[1];

    //point is inside view bounds
    if(( x > viewX && x < (viewX + view.getWidth())) &&
            ( y > viewY && y < (viewY + view.getHeight()))){
        return true;
    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于您可以作为参数传递的布局中的已知视图,我仍然无法通过了解坐标来获取单击的视图.您可以搜索布局中的所有视图.

  • private boolean isPointInsideView(float x, float y, View view) { Rect rect = new Rect(); view.getDrawingRect(rect); 返回 rect.contains((int) x, (int) y); } (9认同)
  • @etienne,请注意getDrawingRect()返回有关滚动视图内部显示的绘图rect的信息.如果要获取嵌套在另一个视图中的视图的矩形,则它不起作用.htafoya的解决方案按预期工作. (6认同)

sch*_*dt9 5

只是为了使htafoya的方法更简单:

/**
* Determines if given points are inside view
* @param x - x coordinate of point
* @param y - y coordinate of point
* @param view - view object to compare
* @return true if the points are within view bounds, false otherwise
*/
private boolean isPointInsideView(float x, float y, View view) {
    int location[] = new int[2];
    view.getLocationOnScreen(location);
    int viewX = location[0];
    int viewY = location[1];

    // point is inside view bounds
    return ((x > viewX && x < (viewX + view.getWidth())) &&
            (y > viewY && y < (viewY + view.getHeight())));
}
Run Code Online (Sandbox Code Playgroud)