Domanda

Sto realizzando un'app, un gioco e voglio che il giocatore sia in grado di utilizzare il pulsante Indietro per saltare (per dispositivi a touch singolo). La mia piattaforma target è 2.1 (livello API 7).

Ho provato sia OnKeyDown () che su OnBackpressed (), ma vengono chiamati solo quando il pulsante viene rilasciato, non quando viene premuto verso il basso.

1) È normale?

2) Come posso farlo in modo che registri la pressione quando viene premuto il pulsante?

EDIT: Vorrei anche aggiungere che funziona correttamente usando una tastiera (OnkeyDown viene chiamato quando viene premuto un tasto).

È stato utile?

Soluzione

AGGIORNAMENTO: Sono stato incuriosito per questo. Dai un'occhiata al codice sorgente Android.View.View: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/view.java

Un esempio tipico sarebbe gestire la chiave posteriore per aggiornare l'interfaccia utente dell'applicazione invece di consentire all'IME di vederlo e chiuderla.

codice:

/**
 * 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;
}

Utilizzando 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;
}

Registri i due eventi in modo indipendente anche per la chiave posteriore. L'unica chiave che non ha registrato era KEYCODE_HOME, per qualche ragione. In effetti, se mantieni il pulsante Indietro premuto, ne vedrai diversi ACTION_DOWN (0) Eventi di fila (e molto altro se tu return false; invece). Testato in un emulatore di eclair e un samsung captive (personalizzato Froyo Rom).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top