Android - 检测长按结束

Ita*_*ayM 20 android touch-event

我正在开发用户需要按住按钮很长时间的应用程序.

如何检测用户的时刻:完成印刷或移动触摸位置?

谢谢

Joh*_*nor 52

我认为你最好的办法就是为该按钮使用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;
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 当我长按按钮时动作运行了两次,我通过在onTouchListener中返回true而不是false来修复它. (4认同)

Ben*_*ane 6

这些答案非常复杂。如果您从退出,则长按结束时onClickOnClickListener静止中调用静止图像。这是检测长按结束的最容易的地方。falseOnLongClickListener

这是为了知道,因为如果实现了尤其重要onTouch途径,同时返回falseonLongClick(默认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
}
Run Code Online (Sandbox Code Playgroud)

如您所见,当您让Android将结束触摸事件传播到时,逻辑变得非常简单OnClickListener