5

I have a main activity that does not use option menu. I need to implement this behavior: 1. When the Android Menu button is pressed, a popup is shown 2. When the Android Menu button is pressed again, the popup is dismissed.

I know how to do #1 by overriding onKeyDown() in the main activity but don't know how to do #2. When the popup is shown, the onKeyDown() of the main activity is not triggered anymore.

How do I capture the Android Menu button when the main activity has an open popup? (in my case, the popup is a PopupWindow with an inflated view).

BTW, I tried to set a key listener on the main view of the popup but it is not triggered

    mTopView.setOnKeyListener(new View.OnKeyListener() {           
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            LogUtil.debug("*** Key: %d", keyCode);
            return false;
        }
    });
user1139880
  • 1,828
  • 3
  • 18
  • 27
  • 1
    If it were me, I would make the "pop-up" into its own activity, that way it can be done the exact same way as in the MainActivity. Just call finish() when menu is pressed in the pop-up activity. – FoamyGuy Jun 26 '12 at 20:31
  • Thanks. I have a lot of code invested in the popup solution (it needs to popup at a specific location and shape in relation to an anchor view). If I will not find a way to make it to work I will try to activity approach. – user1139880 Jun 26 '12 at 21:05

2 Answers2

14

Answering my own question. Calling setFocusableInTouchMode() on the PopupWindow view does the trick and causes the listener to work.

PopupMenu popupMenu = ...
...
popupWindow.getContentView().setFocusableInTouchMode(true);
popupMenu.getContentView().setOnKeyListener(new View.OnKeyListener() {        
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode ==  KeyEvent.KEYCODE_MENU && 
                event.getRepeatCount() == 0 && 
                event.getAction() == KeyEvent.ACTION_DOWN) {
            // ... payload action here. e.g. popupMenu.dismiss();
            return true;
        }                
        return false;
    }
});
user1139880
  • 1,828
  • 3
  • 18
  • 27
0

try this

if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Do Stuff
    } 
Boe-Dev
  • 1,585
  • 2
  • 14
  • 26