按下选项菜单时关闭弹出窗口 [英] dismiss popup when options menu is pressed
问题描述
我实现了一个弹出窗口,当按下硬件菜单键时会弹出该弹出窗口.现在,当我再次按菜单键时,我想关闭弹出窗口.
I implemented a popup which shows up when I press the hardware menu key. Now I want to dismiss the popup when I press on the menu key again.
我尝试过
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (pw.isShowing()) {
pw.dismiss();
} else {
openpopup();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
这是打开弹出窗口的方法
here's the open popup method
public void openpop() {
View view1 = getCurrentFocus();
showpopup(view1);
}
这是showpopup方法
here's the showpopup method
public void showpopup(View view) {
pw.setTouchable(true);
pw.setFocusable(true);
pw.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pw.dismiss();
return true;
}
return false;
}
});
try {
pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setOutsideTouchable(false);
pw.setContentView(popupView);
pw.showAsDropDown(view, 0, 0);
popUpShowed = true;
} catch (Exception e) {
Log.e("SAMPLE", "Exception", e);
}
}
但是当我按菜单时,弹出窗口不会消失.
But the popup is not dismissed when I press menu.
可能是什么问题?我需要以某种方式完成此操作.请帮帮我.
What could be the problem? I need to get this done somehow. Please help me out.
推荐答案
显然,第二次按菜单键不会触发.
在此处找到解决方法.
希望对您有所帮助.
Apparently, pressing Menu Key second time does not trigger.
Found here the solution.
Hope it helps.
检查并创建了另一种方法.这应该做到:
EDIT :
Checked and created another approach. This should do it :
boolean open = false;
boolean itemSelected = false;
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(!open || itemSelected) {
showPopup();
open = true;
itemSelected = false;
}
return false;
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
if (open && !itemSelected) {
closePopup();
open = false;
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
itemSelected = true;
return false;
}
在Android 4.0.3上为我工作.显然,onPrepareOptionsMenu
在v3之后更改了功能.
Works for me on Android 4.0.3. Apparently onPrepareOptionsMenu
has changed functionality after v3.
这篇关于按下选项菜单时关闭弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!