【问题标题】:How can I detect time press duration of button in android?如何检测android中按钮的按下时间?
【发布时间】:2019-06-03 16:27:01
【问题描述】:

我想通过使用setOnTouchListeneronTouch 方法来检测按钮的按下时间

我该怎么做?

【问题讨论】:

标签: android button onpress


【解决方案1】:

您可以使用onTouchListener 来做到这一点

long FirstTouchTime ;
long duration ; 

public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) 
        FirstTouchTime = System.currentTimeMillis();    

    else if (event.getAction() == MotionEvent.ACTION_UP) {
        duration = System.currentTimeMillis(); - FirstTouchTime ;
        //duration value in millisecond 
    }
}

【讨论】:

    【解决方案2】:

    也许是这样的:

    long mLastClickTime;
    
    findViewById(R.id.button).setOnTouchListener(new OnTouchListener() {
          @Override
          public void onTouch(View v, MotionEvent event) {
             if (event.getAction() == MotionEvent.ACTION_DOWN) 
                mLastClickTime = SystemClock.elapsedRealtime();
    
             else if (event.getAction() == MotionEvent.ACTION_UP) {
                long duration = SystemClock.elapsedRealtime() - mLastClickTime;
                // using threshold of 1000 ms
                if (duration > 1000) {
                   // do your magic here
                }
             }
          }    
    });
    

    【讨论】:

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