0

I want to detect time press duration of button by using setOnTouchListener with onTouch method

How I can do this ?

John Joe
  • 12,412
  • 16
  • 70
  • 135
Jason Momoa
  • 123
  • 8
  • Maybe answered here https://stackoverflow.com/questions/22606977/how-can-i-get-button-pressed-time-when-i-holding-button-on – aggaton Jun 03 '19 at 16:29
  • Possible duplicate of [Measure elapsed time between two MotionEvents in Android](https://stackoverflow.com/questions/9764310/measure-elapsed-time-between-two-motionevents-in-android) – Steven Jun 03 '19 at 16:43
  • check my answer – ismail alaoui Jun 03 '19 at 17:02

2 Answers2

0

you can do it using 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 
    }
}
ismail alaoui
  • 5,748
  • 2
  • 21
  • 38
0

Maybe something like this :

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
            }
         }
      }    
});
Faruk
  • 5,438
  • 3
  • 30
  • 46