【问题标题】:how to detect the period for which a button is press in android如何检测在android中按下按钮的时间
【发布时间】:2010-12-10 15:27:00
【问题描述】:

有什么方法可以检测按钮按下了多长时间?我想捕捉按下按钮的时间并采取相应的行动。因此,如果用户持续按下按钮 5 秒,我想在 android 上检测到该 5 秒。

请告诉我

谢谢 普拉奈

【问题讨论】:

  • 如何接受不知道的答案可以告诉我

标签: android android-widget android-layout


【解决方案1】:

使用以下来确定触摸持续时间。您可以在 if 语句中使用它: event.getEventTime() - event.getDownTime() > 5000 它以毫秒为单位计算,这意味着您需要在 5 秒内将此数字设为 5000

不要使用: android.os.SystemClock.elapsedRealtime()-event.getDownTime() 它可能在模拟器上工作,但它不会在设备上工作!不要问我是怎么知道的;)

【讨论】:

    【解决方案2】:

    给按钮一个View.OnTouchListener。您将实现的 onTouch 方法将允许您访问MotionEvent。然后,使用 getFlags(),您将知道用户何时开始按下按钮 (ACTION_DOWN) 以及何时停止 (ACTION_UP)。只需记录这些发生时的系统时间(或者按照另一个答案中的建议, getDownTime() 将给出您需要的时间,但仅当您有 ACTION_UP 标志时)。

    【讨论】:

      【解决方案3】:
          private long timeElapsed = 0L; //make this a global variable
      
          //tvTouches could be a TextView or Button or other views
          tvTouches.setOnTouchListener(new View.OnTouchListener() {
              @Override
              public boolean onTouch(View v, MotionEvent event) {
                  switch (event.getAction()) {
                      case MotionEvent.ACTION_DOWN:
                          timeElapsed = event.getDownTime();
                          Log.d("setOnTouchListener", "ACTION_DOWN at>>>" + event.getDownTime());
                          break;
                      case MotionEvent.ACTION_UP:
                          timeElapsed = event.getEventTime() - timeElapsed;
                          Log.d("setOnTouchListener", "ACTION_UP at>>>" + event.getEventTime());
                          Log.d("setOnTouchListener", "Period of time the view is pressed>>>" + timeElapsed);
                          Toast.makeText(getApplicationContext(), "Period of time the view is pressed in milliseconds>>>" + timeElapsed, Toast.LENGTH_SHORT).show();
                          timeElapsed = 0L;
                          //TODO do something when a certain period of time has passed
                          break;
                      default:
                          break;
                  }
                  return true;
              }
          });
      

      【讨论】:

        【解决方案4】:

        在 Button 上注册一个 OnTouchListener。然后在监听器中使用 MotionEvent:

        http://developer.android.com/reference/android/view/MotionEvent.html

        然后使用Event的getDownTime()方法:

        http://developer.android.com/reference/android/view/MotionEvent.html#getDownTime%28%29

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-05
          • 1970-01-01
          • 2017-08-09
          相关资源
          最近更新 更多