views:

247

answers:

3

I want to do a custom action when pressing on the Menu button on the phone.

Is it possible to set an onClickListener (or similar) on the button and if so, how?

onCreateOptionsMenu is only called the first time the button is pressed - I've already tried this.

A: 

You could probably hack something in using "OnMenuOpened" or some such, but I really wouldn't recommend it. The menu button is only supposed to be used to show menus, so there is consistency between applications.

Mayra
+1  A: 

But onPrepareOptionsMenu(..) is called each time. :)

alex
Not a very long answer, but this is the way to do it! As he said, it's called every time before the menu actually appears, so you can customise your menu in that.
Steve H
+3  A: 

Usually you shouldn't override MENU behavior as users expect menu to appear, however you can use something along these lines:

/* (non-Javadoc)
 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ( keyCode == KeyEvent.KEYCODE_MENU ) {
        Log.d(TAG, "MENU pressed");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
dtmilano
Thanks - this is what I was looking for. And dont worry - I'm not gona change the user experience but i want to do some custom actions before the menu is actually rendered.
Mannaz