Differentiate Regular Menu KeyEvent from IME Opening
Asked Answered
C

1

7

In listening for key events in ActionBarSherlock in order to show the overflow menu on pre-ICS devices and am I'm facing an interesting problem. It would seem that I am unable to differentiate a simple key press versus when the user is long-pressing the menu key with the intention of displaying the IME. Both KeyEvent instances are exactly the same and look like this:

Is there a straightforward way to differentiate between these two distinct events?

Cosmology answered 29/3, 2012 at 18:4 Comment(1)
Using the onPrepareOptionsMenu callback is my fallback but I'd prefer to handle it via key events.Cosmology
G
4

Hmmmm... onLongKeyPress() does not seem to work with KEYCODE_MENU. How annoying.

This seems to work on the Nexus S (4.0.3) and Nexus One (2.3.6):

public class MenuKeyDetectorActivity extends Activity {
  boolean wasLongPress=false;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
      wasLongPress=wasLongPress | event.isLongPress();
    }

    return(false);
  }

  @Override
  public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
      Log.w("MKD", String.format("wasLongPress: %b", wasLongPress));
      wasLongPress=false;
    }

    return(false);
  }
}

Basically, note whether it is a long-press or not in your onKeyDown() calls, then use that information in onKeyUp() to determine the final disposition.

Greeley answered 29/3, 2012 at 18:35 Comment(1)
Hoping this technique will work with onKeyEvent and detecting the up/down action. I don't see why it wouldn't. Thanks!Cosmology

© 2022 - 2024 — McMap. All rights reserved.