2012-03-03 85 views
0

的確切面積是現在我的代碼:按屏幕上

public boolean onTouchEvent(MotionEvent event) 
     { 
      int action = event.getAction(); 

      switch(action) 
      { 
       case MotionEvent.ACTION_DOWN: 
       // Do click work here ... 
       Y -= 10; 
       Yopen = 1; 
       break; 
       case MotionEvent.ACTION_UP: 
       // Do release work here ... 
       Yopen = 0; 
       break; 
       } 

      return super.onTouchEvent(event); 
    } 

但我想讓只有三個不同的區域執行不同的代碼。 有人可以幫助我,在互聯網上的一些很好的教程。

回答

0

此代碼添加到您的onTouchEvent找出使用者觸摸的位置和適當的迴應:

//Grab the current touch coordinates 
    float x = event.getX(); 
    float y = event.getY(); 

    //If you only want something to happen then the user touches down... 
    if (event.getAction() != MotionEvent.ACTION_UP) return true; 

    //If the user pressed in the following area, run it's associated method 
    if (isXYInRect(x, y, new Rect(x1, y1, x2, y2))) 
    { 
     //Do whatever you want for your defined area 
    } 
    //or, if the user pressed in the following area, run it's associated method 
    else if (isXYInRect(x, y, new Rect(x1, y1, x2, y2))) 
    { 
     //Do whatever you want for your defined area 
    } 

這裏的isXYinRect方法:

//A helper method to determine if a coordinate is within a rectangle 
private boolean isXYInRect(float x, float y, Rect rect) 
{ 
    //If it is within the bounds... 
    if (x > rect.left && 
     x < rect.right && 
     y > rect.top && 
     y < rect.bottom) 
    { 
     //Then it's a hit 
     return true; 
    } 

    //Otherwise, it's a miss 
    return false; 
}