android 新版本已经不推荐使用menu键,虽然api隐藏了,但还是可以通过反射的方式进行调用
对于sdk版本小于21(包含)的可以用Window 的addFlags 获取clearFlags的方法开启或关闭
对于sdk版本大于21的可以通过给WindowManager.LayoutParams 的 needsMenuKey设置相应的值来进行开启或关闭
封装成一个方法
public void setVirtualMenu(boolean flag){
try {
if (Build.VERSION.SDK_INT > 21) {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
WindowManager.LayoutParams.class.getField("needsMenuKey").set(layoutParams, flag ? 1 : 2);
getWindow().setAttributes(layoutParams);
} else if (Build.VERSION.SDK_INT <= 21) {
if (flag) {
getWindow().addFlags(WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null));
} else {
getWindow().clearFlags(WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null));
}
}
}catch (NoSuchFieldException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
}
}