dan dan - 1 year ago 146
Android Question

Android key event for back key when soft keyboard is shown?

I am trying to capture the "back" key event when the soft keyboard is shown.

I am using SDK ver 8 and can successfully capture the back key event ONLY when the soft keyboard is HIDDEN as follows:

public void onBackPressed() {
// do something

The problem is that the system is not calling this method while the soft keyboard is shown. I have tried to log onKeyDown/Up() methods as well as the above method to work out what is happening in this scenario to no avail. See below:

public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.d(TAG + "KeyUP", String.valueOf(event));

Logs are returned for volume and menu keys as expected but the back key is only logged when the soft keyboard and menu are hidden.

Are there any "back key" guru's out there that can explain this phenomenon?

Any help is greatly appreciated.

dan dan
Answer Source

After digging around further on this site and the Android API I have found that


is caught and gobbled up by an IME that has an input method connection and that input method is currently shown (in other words; the soft keyboard is NOT hidden). This means that the event is consumed before the system calls the Activity classes onKeyDown() or onKeyUp() methods.

To get around this, create a sub-class of your IME widget (TextView or its child classes such as EditText) and implement onKeyPreIme().

Stack user i2097i has posted a good solution to implementing onKeyPreIme() in an activity here. Just make sure to return FALSE in your onKeyPreIme() Override if you wish to retain Androids default behaviour (i.e. closing the keyboard).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download