2014-01-30 60 views
2

我有一個按鈕,我在按鈕按動畫。當我拖出特定的閾值之後,我希望它恢復到「正常」狀態。如何讓我的視圖在ACTION_MOVE後停止監聽觸摸事件?

我在ACTION_DOWN上創建了一個矩形的視圖邊界,並檢查它是否在ACTION_MOVE的觸摸區域之外。我成功地發現了「越界」觸摸,但我無法停止觀看觸摸。這就像它忽略了我的animateToNormal()方法。

我試着改變布爾返回值爲true而不是false,這沒有幫助。我也嘗試在ACTION_MOVE的情況下刪除觸摸偵聽器(設置爲空),但我需要重新連接以繼續偵聽觸摸。我想我可以在添加它之前添加一個任意延遲,但這似乎是一個可怕的黑客。

我在4.2設備(LG G2)上測試這個。

private static class AnimationOnTouchListener implements View.OnTouchListener { 
     private Rect rect; 

     @Override 
     public boolean onTouch(View view, MotionEvent motionEvent) { 

      switch(motionEvent.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); 
        animatePressed(); 
        return false; 

       case MotionEvent.ACTION_CANCEL: 
       case MotionEvent.ACTION_UP: 
        // back to normal state 
        animateBackToNormal(); 
        return false; 

       case MotionEvent.ACTION_MOVE: 
        if(!rect.contains(view.getLeft() + (int) motionEvent.getX(), view.getTop() + (int) motionEvent.getY())){ 
         d(TAG, "out of bounds"); 
         animateBackToNormal(); 
         // STOP LISTENING TO MY TOUCH EVENTS! 

        } else { 
         d(TAG, "in bounds"); 
        } 
        return false; 
       default: 
        return true; 
      } 
     } 
+0

好笑的是,我有相反的問題。我想繼續收到活動,但是我沒有。 http://stackoverflow.com/questions/34908569/android-continue-receiving-touch-events-in-a-view-after-the-touch-is-dragged –

回答

6

爲什麼你只是不聽,但設置一個語句來忽略動作事件?

類似的東西:

private static class AnimationOnTouchListener implements View.OnTouchListener { 
     private Rect rect; 
     private boolean ignore = false; 

    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 
     if(ignore && motionEvent.getAction()!=MotionEvent.ACTION_UP) 
      return false; 
     switch(motionEvent.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); 
       animatePressed(); 
       return false; 

      case MotionEvent.ACTION_CANCEL: 
      case MotionEvent.ACTION_UP: 
       // back to normal state 
       animateBackToNormal(); 

       // IMPORTANT - touch down won't work if this isn't there. 
       ignore = false; 
       return false; 

      case MotionEvent.ACTION_MOVE: 
       if(!rect.contains(view.getLeft() + (int) motionEvent.getX(), view.getTop() + (int) motionEvent.getY())){ 
        d(TAG, "out of bounds"); 
        animateBackToNormal(); 
        // STOP LISTENING TO MY TOUCH EVENTS! 
        ignore = true; 
       } else { 
        d(TAG, "in bounds"); 
       } 
       return false; 
      default: 
       return true; 
     } 
    } 
+0

我誤解了返回值的作用。謝謝!我確實需要對代碼進行一次調整(在ACTION_UP中添加'ignore = false;',但總體來說可行! – loeschg

+0

只需要提一下,這對我來說似乎是一個快速的解決方案,但不是最好的,如果您發現「更多的「正確的解決方案,請在這個帖子中發帖 – GhostDerfel

+0

你說得好,我不會再接受你的答案再鼓勵別人發帖,我會接受的,如果沒有其他答案的話 – loeschg

相關問題