如何在Android中检测按钮按下的持续时间?

时间:2019-06-03 16:27:01

标签: android button onpress

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

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以使用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 
    }
}

答案 1 :(得分:0)

也许是这样的:

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
            }
         }
      }    
});