Capturing Android Menu Button in PopupWindow

I have a basic action that does not use the options menu. I need to implement this behavior: 1. When the Android Menu button is pressed, a popup window is displayed 2. When the Android Menu button is pressed again, the popup window is rejected.

I know how to do # 1 by overriding onKeyDown () in the main action, but I don’t know how to do # 2. When the popup appears, onKeyDown () of the main action no longer starts.

How can I grab the Android Menu button when the main action has an open popup? (in my case, the popup is a PopupWindow with a bloated view).

By the way, I tried to set the key listener in the main view of the popup, but it does not start

    mTopView.setOnKeyListener(new View.OnKeyListener() {           
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            LogUtil.debug("*** Key: %d", keyCode);
            return false;
        }
    });
+5
source share
2 answers

Answering my question. Calling setFocusableInTouchMode () on the PopupWindow view does the trick and makes the listener 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;
    }
});
+14
source

try it

if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Do Stuff
    } 
0
source

All Articles