2011-05-31 74 views
12

我正在處理用戶需要長時間按住按鈕的應用程序。Android - 長按檢測結束

我該如何檢測用戶:完成按鍵或移動觸摸位置的時刻?

感謝

+0

您需要解釋爲什麼用戶移動位置很重要。至於檢測長按的結束,只需使用setOnLongClickListener()。 onLongClick()方法將在用戶釋放按鈕時自動調用。 – Squonk 2011-05-31 08:06:00

+2

這是錯誤的 - 只要檢測到長時間點擊,onLongClick方法就會被觸發 - 例如:一旦發生「長按」的超時,而不是當用戶釋放按鈕時。 – 2012-05-24 22:43:10

回答

37

我認爲你最好的選擇是使用該按鈕的onLongClickListener()和onTouchListener()的組合。您需要捕捉觸摸偵聽器上的某些事件,因爲它會觸發每個觸摸事件。

嘗試類似如下:

class Blah extends Activity { 
    private Button mSpeak; 
    private boolean isSpeakButtonLongPressed = false; 

    @Override 
    public void onCreate(Bundle icicle) { 
      super.onCreate(icicle); 
      setContentView(R.layout.blahlayout); 
      Button mSpeak = (Button)findViewById(R.id.speakbutton); 
      mSpeak.setOnLongClickListener(speakHoldListener); 
      mSpeak.setOnTouchListener(speakTouchListener); 
    } 

    private View.OnLongClickListener speakHoldListener = new View.OnLongClickListener() { 

      @Override 
      public boolean onLongClick(View pView) { 
       // Do something when your hold starts here. 
       isSpeakButtonLongPressed = true; 
       return true; 
      } 
    } 

    private View.OnTouchListener speakTouchListener = new View.OnTouchListener() { 

      @Override 
      public boolean onTouch(View pView, MotionEvent pEvent) { 
       pView.onTouchEvent(pEvent); 
       // We're only interested in when the button is released. 
       if (pEvent.getAction() == MotionEvent.ACTION_UP) { 
        // We're only interested in anything if our speak button is currently pressed. 
        if (isSpeakButtonLongPressed) { 
         // Do something when the button is released. 
         isSpeakButtonLongPressed = false; 
        } 
       } 
       return false; 
      } 
    } 
} 
+0

這對我有效,謝謝! – 2014-09-08 19:36:44

+0

謝謝約翰,很好的解決方案。 – alfdev 2015-09-14 14:06:34

+3

當我長按按鈕時,該動作運行了兩次,我通過在onTouchListener中返回true而不是false來修復它。 – DAVIDBALAS1 2016-07-23 13:41:11

2

這些答案是相當複雜的。 onClickOnClickListener仍然會在長按結束時被調用,如果您返回false。這是檢測長按結束的最簡單的地方。

這是要知道,因爲如果實現了onTouch路線在返回從onLongClickfalse尤其重要(默認AS給你,往往你想要的),你onClick代碼可能在你長按結束被稱爲沒有你意識到這一點。

下面是基於捕捉的照片或視頻的例子:

private boolean takingVideo = false; 

captureButton.setOnClickListener(v -> { 
    // onClick gets called after normal click or long click 
    if(takingVideo) { 
     saveVideo(); 
    } else { 
     takePhoto(); 
    } 
}); 

captureButton.setOnLongClickListener(v -> { 
    takeVideo(); 

    return false; 
}); 

private void takePhoto() { 
    // Save the photo 
} 

private void takeVideo() { 
    takingVideo = true; 
    // Start capturing video 
} 

private void saveVideo() { 
    takingVideo = false; 
    // Save the video 
} 

正如你所看到的,邏輯就變得非常簡單,當你讓Android爲傳播結束觸摸事件的OnClickListener