Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

how to get a view from an event coordinates in android?

I want to intercept the touch events on my parent view with onInterceptTouchEvent (MotionEvent ev).

From there I want to know which view was clicked in order to do other things, is there any way to know which view was clicked from that motion event received?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well for anyone who wants to know what I did ... i couldn't. I did a workaround to just know if my specific view component was clicked, so I could only end with this:

   if(isPointInsideView(ev.getRawX(), ev.getRawY(), myViewComponent)){
    doSomething()
   }

and the method:

/**
 * 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;
    }
}

However this only works for known views in the layout that you can pass as parameter, I still can't get the clicked view just by knowing the coordinates. You may search for all views in the layout though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...