Pregunta

Estoy haciendo una aplicación, un juego, y quiero que el jugador pueda usar el botón de retroceso para saltar (para dispositivos de un solo toque). Mi plataforma objetivo es 2.1 (Nivel API 7).

He probado tanto OnKeyDown () como OnbackProssed (), pero solo se llaman cuando se libera el botón Atrás, no cuando se presiona hacia abajo.

1) ¿Es esto normal?

2) ¿Cómo puedo hacerlo para que registre la presión cuando se presiona el botón?

Editar: también me gustaría agregar que funciona correctamente usando un teclado (OnKeydown se llama cuando se presiona una tecla).

¿Fue útil?

Solución

Actualización: me dio curiosidad por esto. Eche un vistazo al código fuente android.view.view: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/view.java

Un ejemplo típico sería manejar la clave posterior para actualizar la interfaz de usuario de la aplicación en lugar de permitir que el IME lo vea y se cierre.

código:

/**
 * Handle a key event before it is processed by any input method
 * associated with the view hierarchy.  This can be used to intercept
 * key events in special situations before the IME consumes them; a
 * typical example would be handling the BACK key to update the application's
 * UI instead of allowing the IME to see it and close itself.
 *
 * @param keyCode The value in event.getKeyCode().
 * @param event Description of the key event.
 * @return If you handled the event, return true. If you want to allow the
 *         event to be handled by the next receiver, return false.
 */
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    return false;
}

Uso de DispatchKeyEvent:

@Override
public boolean dispatchKeyEvent (KeyEvent event) {
    Log.d("**dispatchKeyEvent**", Integer.toString(event.getAction()));
    Log.d("**dispatchKeyEvent**", Integer.toString(event.getKeyCode()));
    if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
        Toast.makeText(this, "Back button pressed", Toast.LENGTH_LONG).show();
        return true;
    }
    return false;
}

Registra los dos eventos de forma independiente incluso para la tecla de atrás. La única clave que no registró fue KEYCODE_HOME, por alguna razón. De hecho, si mantiene presionado el botón Atrás, verá varios ACTION_DOWN (0) eventos seguidos (y mucho más si return false; en cambio). Probado en un emulador Eclair y un Samsung Captivate (ROM Froyo personalizado).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top