Masked Man
Masked Man

Reputation: 2558

Which key action does the nexus phone fire when back button pressed?

I'm wondering which KeyEvent action is called when a user presses the little upside-down triangle in nexus phone when soft keyboard is open.

In normal mode Nexus looks like this and the normal code works fine: Nexus without keyboard

But when keyboard pops up it looks like this and the code won't work:

Nexus with keyboard

Upvotes: 0

Views: 191

Answers (1)

Giacomo Mattiuzzi
Giacomo Mattiuzzi

Reputation: 305

For android API up to 5:

    @Override
public void onBackPressed() {
    // your code.
}

For android before API 5 you must use this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Please refer to How to handle back button in activity

EDIT:

This methods works only if the keyboard is hidden..

according with this answer: Detect back key press - When keyboard is open

The best action to be implement is dispatchKeyEventPreIme. An example is:

@Override
    public boolean dispatchKeyEventPreIme(KeyEvent event) {
        Log.d(TAG, "dispatchKeyEventPreIme(" + event + ")");
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            KeyEvent.DispatcherState state = getKeyDispatcherState();
            if (state != null) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getRepeatCount() == 0) {
                    state.startTracking(event, this);
                    return true;
                } else if (event.getAction() == KeyEvent.ACTION_UP
                        && !event.isCanceled() && state.isTracking(event)) {
                    mActivity.onBackPressed();
                    return true;
                }
            }
        }

        return super.dispatchKeyEventPreIme(event);
    }

Where mActivity is your activity class (this).

Upvotes: 2

Related Questions