Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate Regular Menu KeyEvent from IME Opening

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?

like image 981
Jake Wharton Avatar asked Mar 29 '12 18:03

Jake Wharton


1 Answers

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.

like image 127
CommonsWare Avatar answered Oct 21 '22 05:10

CommonsWare