2010-09-24 10 views
27

¿Es posible capturar la liberación de un botón al igual que capturamos, haga clic usando onClickListener() y OnClick()?Lanzamiento del botón de captura en Android

Quiero aumentar el tamaño de un botón cuando se lo presiona y moverlo al tamaño original cuando se suelta. ¿Alguien puede ayudarme a hacer esto?

Respuesta

47

Debe establecer OnTouchListener en su botón.

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(); 
     } 
    } 
}; 
+0

OnTouchListener solo escucha tocar, ¿verdad? Quiero escuchar clic y lanzar. Cómo ir abt it? – mdv

+1

Un evento táctil hacia abajo y arriba es prácticamente un clic. También puede configurar un onclicklistener y un ontouchlistener en el botón. –

+4

Me pregunto por qué kiki recibió la respuesta aceptada, ya que creo que me dio una respuesta más precisa. –

1

Puede hacer esto sobrescribiendo onKeyDown y onKeyUp. Ambos son heredados de android.widget.TextView. Por favor, consulte el android.widget.Button doc para (un poco) más información.

+1

onKeyDown y onKeyUp es para eventos de teclado si no estoy equivocado. ¿Es posible capturar eventos de clic para ellos? – mdv

2

utilice OnTouchListener u OnKeyListener en su lugar.

0

Eric Nordvik tiene la respuesta correcta, excepto que

event.getAction() == MotionEvent.ACTION_UP 

nunca nos ejecutada por mí. En cambio implementé

button.setOnClickListener(new OnClickListener() { 
     @Override 
     public boolean onClick(View v) { 
      resetSize();  
    } 
}; 

para el toque ACTION_UP.

3

Usted tiene que manejar MotionEvent.ACTION_CANCEL también. Entonces el código será:

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