2012-08-15 17 views
16

Me gustaría iniciar un temporizador que comienza cuando se presiona un botón por primera vez y finaliza cuando se suelta (básicamente quiero medir cuánto tiempo se mantiene presionado un botón). Usaré el método System.nanoTime() en ambos momentos, luego restaré el número inicial del último para obtener una medición del tiempo transcurrido mientras el botón se mantuvo presionado.Cómo detectar cuando se presiona y suelta el botón en android

(Si tienes alguna sugerencia para el uso de algo que no sea nanoTime() o alguna otra forma de medir el tiempo que se mantenga pulsado un botón, estoy abierto a esos también.)

Gracias! Andy

+0

similares a este SO mensaje: http://stackoverflow.com/q/4410362/2069407 –

Respuesta

28

Uso OnTouchListener en lugar de OnClickListener:

// this goes somewhere in your class: 
    long lastDown; 
    long lastDuration; 

    ... 

    // this goes wherever you setup your button listener: 
    button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     if(event.getAction() == MotionEvent.ACTION_DOWN) { 
      lastDown = System.currentTimeMillis(); 
     } else if (event.getAction() == MotionEvent.ACTION_UP) { 
      lastDuration = System.currentTimeMillis() - lastDown; 
     } 

     return true; 
    } 
    }); 
+0

nos proporcione el código que ha hecho por el clic de botón –

+0

Por desgracia, este no funciona cuando se presiona el botón con el teclado. Solo funciona cuando se toca. –

+0

Entonces, ¿quieres ver cuánto tiempo se presiona un botón del teclado? – Nick

4
  1. En onTouchListener iniciar el temporizador.
  2. En onClickListener, detenga los tiempos.

calcule el differece.

5

Esto sin duda trabajar:

button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     if(event.getAction() == MotionEvent.ACTION_DOWN) { 
      increaseSize(); 
     } else if (event.getAction() == MotionEvent.ACTION_UP) { 
      resetSize(); 
     } 
     return true; 
    } 
}); 
Cuestiones relacionadas