martes, 8 de noviembre de 2011

Una actividad para leer pulsaciones del teclado

Se empieza declarando que la Actividad implementa el interfaz  OnKeyListener.
  public class PruebaLectorPulsacionesTeclado extends Activity implements OnKeyListener
Sobreescribimos el metodo onCreate de la actividad
  @Override public void onCreate(Bundle savedInstanceState)
y en él declaramos un TextView para mostar el texto.
  TextView textView = new TextView(this);
y le diremos que se "subscriba" a  OnKeyListener.
  textView.setOnKeyListener(this);
Para que reciba los eventos de teclado el textView debe tener el foco por lo tanto haremos
  textView.setFocusableInTouchMode(true);
  textView.requestFocus();

Despues debemos sobreescribir el método onKey de android.view.View.OnKeyListener
public abstract boolean onKey (View v, int keyCode, KeyEvent event)
Interface definition for a callback to be invoked when a key event is dispatched to this view. The callback will be invoked before the key event is given to the view. Called when a key is dispatched to a view. This allows listeners to get a chance to respond before the target view. Parameters
  v     The view the key has been dispatched to.
  keyCode     The code for the physical key that was pressed
  event     The KeyEvent object containing full information about the    event.
Returns
  True if the listener has consumed the event, false otherwise.

La implementación:
 @Override public boolean onKey(View view, int keyCode, KeyEvent event)
en él procesaremos dos eventos el .ACTION_DOWN y .ACTION_UP es decir cuando se pulsa y cuando se suelta la tecla. ¿Como se hace esto?
Con event.getAction()
    switch (event.getAction())
    {
        case KeyEvent.ACTION_DOWN:
        {};
        break;
        case KeyEvent.ACTION_UP:
        {};
        break;
    }
Este método debe devolver un booleano por lo que al final del método  pondremos
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
            return false;
    else
            return true;
¿Esto para que? Esa es la tecla de ir para atrás, lo que haria que salieramos de la aplicación.Si no hicieramos esto esa tecla no haria nada y no podriamos salir de la actividad con ella.

No hay comentarios:

Publicar un comentario