Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting Android Menu button in a PopupWindow

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;
        }
    });
like image 516
user1139880 Avatar asked Jun 26 '12 20:06

user1139880


1 Answers

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;
    }
});
like image 169
user1139880 Avatar answered Nov 03 '22 01:11

user1139880