Pergunta

I am making an app, a game, and I want the player to be able to use the back button for jumping(for single-touch devices). My target platform is 2.1(API level 7).

I've tried both onKeyDown() and onBackPressed(), but they are only called when the back button is RELEASED, not when it is pressed down.

1) Is this normal?

2) How can I make it so it registers the press when the button is pressed?

EDIT: I'd also like to add that it works correctly using a keyboard(onKeyDown is called when a key is pressed down).

Foi útil?

Solução

Update: I got curious about this. Take a look at the android.view.View source code: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View.java

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.

code:

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

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

Logs the two events independently even for the back key. The only key that did not log was KEYCODE_HOME, for some reason. In fact, if you maintain the back button pressed, you will see several ACTION_DOWN (0) events in a row (and much more if you return false; instead). Tested in an Eclair emulator and a Samsung Captivate (custom Froyo ROM).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top