2011-05-31 76 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