2013-06-22 10 views
0

這裏是我使用的代碼:我使用onClick事件爲單一的水龍頭事件Android的 - 接受錯誤的觸摸事件

// Handling Touch Events 
@Override 
public boolean onTouch(View view, MotionEvent motionEvent) { 

    float onOffBitmapWidth = this.onOffBitmap.getWidth(); 
    if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 

     if (this.touchMove) { 
      if (togglePositionX > this.onOffBitmap.getWidth()/4.0f) { 
       togglePositionX = this.onOffBitmap.getWidth()/2.0f - this.toggleBitmap.getWidth()/4.0f; 
      } else if (togglePositionX <= this.onOffBitmap.getWidth()/4.0f) { 
       togglePositionX = 0.0f; 
      } 

      this.invalidate(); 
      this.touchMove = false; 
      return true; 

     } else { 

      return false; 

     } 

    } else if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { 

     this.touchMove = false; 
     this.invalidate(); 

    } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) { 

     this.touchMove = true; 

     float currentX = motionEvent.getX(); 

     if (currentX > 0.0f && currentX < (this.onOffBitmap.getWidth()/2.0f - this.toggleBitmap.getWidth()/4.0f)) { 
      togglePositionX = currentX; 
     } else if (currentX >= (this.onOffBitmap.getWidth()/2.0f - this.toggleBitmap.getWidth()/4.0f)) { 
      togglePositionX = this.onOffBitmap.getWidth()/2.0f - this.toggleBitmap.getWidth()/4.0f; 
     } else if (currentX <= 0.0f) { 
      togglePositionX = 0.0f; 
     } 

     this.invalidate(); 
     return true; 

    } 

    return true; 

} 

@Override 
public void onClick(View v) { 

    if (togglePositionX == 0.0f) { 
     togglePositionX = this.onOffBitmap.getWidth()/2.0f - this.toggleBitmap.getWidth()/4.0f; 
    } else { 
     togglePositionX = 0.0f; 
    } 

    this.invalidate(); 

} 

。問題是即使我只點擊屏幕,也會調用ACTION_MOVE。我甚至以一種有趣的方式(用我的手指尖)做到這一點。

+0

對於ACTION_MOVE,是事件的X和Y值實際改變? – Flynn81

+0

它只被調用一次 –

回答

1

我最終使用含有觸摸位置的用戶執行對視圖+一個標誌來檢測閹它是一個真正ACTION_MOVE或不歷史上的一個數組列表。這裏是我實施的代碼if (motionEvent.getAction() == MotionEvent.ACTION_MOVE)

float currentX = motionEvent.getX(); 
     this.userTouchMoveArray.add(currentX); 

     if (this.userTouchMoveArray.size() == 1) { 
      touchIsMoved = false; 
     } else { 
      float oldestX = userTouchMoveArray.get(0); 
      if (Math.abs(currentX - oldestX) > 2.0f) { 
       touchIsMoved = true; 
      } else { 
       touchIsMoved = false; 
      } 
     } 

工作就像一個魅力。 (你可以定義自己的寬容,我在這裏使用2個像素)