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;
}
});
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With