Sunday, 31 October 2010

Android: Menu button click event

If you want to do smth after hardware MENU button clicks, not default menu creation but something slightly different.The easiest way is to capture the onKeyDown event for the menu button click

 @Override
 public boolean onKeyDown(int keycode, KeyEvent event ) {
  if(keycode == KeyEvent.KEYCODE_MENU){
   AlertDialog.Builder dialogBuilder 
   = new AlertDialog.Builder(this)
   .setMessage("Test")
   .setTitle("Menu dialog");
   dialogBuilder.create().show();
  }
  return super.onKeyDown(keycode,event);  
 }
Books:
Professional Android 4 Application Development (Wrox Professional Guides)

3 comments:

  1. Suppose if I show a dialog or popupwindow on the press of android menu button... and I want to hide that dialog or popupwindow when I again click on the android menu button?
    Can you give some tips on this?

    ReplyDelete
  2. The solution is to use custom dialog and methods
    dismissDialog() and showDialog(), but now this method are deprecated google recommend DialogFragment class here is source

    http://developer.android.com/reference/android/app/Activity.html#dismissDialog(int)

    ReplyDelete
  3. The onKeyDown() example above does not seem to work when a dialog or a PopupWindow is opened. Sergey's question includes the challenge of dismissing the dialog when the menu key is pressed the second time. Any suggestion?

    ReplyDelete