Android - 检测长按结束

标签 android touch-event

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

我如何检测用户的时刻:完成按下或移动他们的触摸位置?

谢谢

最佳答案

我认为您最好的选择是对该按钮使用 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;
          }
     }
}

关于Android - 检测长按结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6183874/

相关文章:

selenium - WebDriver 模拟桌面浏览器中的触摸事件

swift - UIWebView 和触摸事件

ios - Coreplot plotSymbolWasSelectedAtRecordIndex on touch up

android - Android LinearLayout中TextView的拖动实现方法

android - 服务的 startActivityForResult 模拟

android - 导出一个APK库工程,在另一个Android工程中使用

android - onSaveInstanceState 和 fragment ?

android - 防止 RecyclerView 消费触摸事件

android - 将触摸事件传递到下方 View 取决于上方 View 触摸

android - 如何跟踪通过我的 Android 应用程序发出的所有 api 请求