0

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

Masked Man
  • 2,176
  • 2
  • 22
  • 41
  • @Override public void onBackPressed() {} – JCDecary Aug 02 '16 at 13:02
  • @JCDecary I used onKeyDown(), when the keyboard is hidden and the triangle points to the left I get the the KeyEvent.KEYCODE_BACK but in keyboard presence I don't know what it fires up! – Masked Man Aug 02 '16 at 13:08
  • maybe this will help you : http://android-developers.blogspot.ca/2009/12/back-and-other-hard-keys-three-stories.html .Im not sur what you want – JCDecary Aug 02 '16 at 13:14

1 Answers1

2

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).

Community
  • 1
  • 1