2010-11-12 39 views
24

我想用onInterceptTouchEvent (MotionEvent ev)截取我父視圖上的觸摸事件。如何從android中的事件座標獲取視圖?

從那裏我想知道爲了做其他事情而點擊了哪個視圖,是否有任何方法可以知道從接收到的動作事件中點擊了哪個視圖?

回答

80

對於任何想要知道我做過什麼的人,我都做不到。我做了一個解決辦法,只是知道我具體的視圖組件被點擊,所以我只能這樣結束:

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

和方法:

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

但是這隻能在已知的意見佈局,你可以作爲參數傳遞,我仍然無法通過知道座標來獲取點擊的視圖。您可以搜索佈局中的所有視圖。

+9

私人布爾isPointInsideView(浮動的x,浮Y,查看視圖){ \t \t矩形RECT =新的Rect(); \t \t view.getDrawingRect(rect); \t \t return rect.contains((int)x,(int)y); \t} – etienne 2011-10-26 10:56:42

+0

建議:偉大的方法候選人被製成靜態。 – m0skit0 2012-09-07 11:59:17

+6

@etienne,請注意,getDrawingRect()返回滾動視圖內顯示的繪圖矩形的信息。如果要獲取嵌套在另一個視圖中的視圖的矩形,它不起作用。 htafoya的解決方案按預期工作。 – sulai 2012-11-22 13:43:15

3

獲取觸摸視圖的一種簡單方法是將OnTouchListener設置爲單個視圖並將視圖存儲在活動的類變量中。 返回false將使輸入事件可用於活動的onTouchEvent()方法,您可以在其中輕鬆處理所有觸摸事件(也是您的父視圖的事件)。

myView.setOnTouchListener(new OnTouchListener() { 
    public boolean onTouch(View v, MotionEvent event) { 
    touchedView = myView; 
    return false; 
    } 
}); 


@Override 
public boolean onTouchEvent(MotionEvent event) { 


    switch (event.getAction()) { 

     case MotionEvent.ACTION_UP: 

      if(touchedView!=null) { 
       doStuffWithMyView(touchedView); 
      .... 
      .... 
3

只是爲了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()))); 
} 
+0

從上面重複我的評論:view.getLocationOnScreen對我來說真的沒有用 - 我認爲它可能會返回視圖的中心座標,因此點擊必須位於視圖的右下角,以便測試返回true ,所以這個例子中的邊界檢查是錯誤的。相反,使用此測試:(x> = view.getLeft()&& x <= view.getRight())&&(y> = view.getTop()&& y <= view.getBottom())。 – gjgjgj 2017-03-23 23:50:10

相關問題