我通过拦截菜单键并在活动上调用 openOptionsMenu() 解决了这个问题。这是关键的监听器:
OnKeyListener mMenuKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_MENU) {
activity.openOptionsMenu();
return true;
} else {
return false;
}
}
};
我认为您必须将此关键侦听器添加到 PopupWindow 中的每个视图才能使其正常工作,因此我编写了一个函数来做到这一点:
public void setupMenuKeyListenerRecursive(View v) {
if (v != null) {
try {
ViewGroup viewGroup = (ViewGroup)v;
int childCount = viewGroup.getChildCount();
for (int index = 0; index < childCount; index++) {
View child = viewGroup.getChildAt(index);
setupMenuKeyListenerRecursive(child);
}
} catch (Exception e) {
}
v.setOnKeyListener(mMenuKeyListener);
}
}