问题
I am building my App with API level 10. But it can be installed and used in later versions. I need to show Action Bar only if the device does not have menu button. For Example, Tablets, Google Galaxy Nexus Phone, etc. People suggest to use hasPermanentMenuKey() function. But it is available only after API level 14 I guess. Can anyone suggest me how to get around this issue?
Thanks, Karthik
回答1:
Use Below code :
ViewConfiguration.get(context).hasPermanentMenuKey();
First set your build target to API level 14 or UP that will stop Eclipse from getting Any Error while Using above code.
Now Check your API Level
Case 1. if your API level : 10 and less
the device does have hardware menu button.
Case 2. if your API level : 11 to 13(HoneyComb)
the device doesn't have HW MENU button, because tablets with Honeycomb doesn't have MENU.
Case 3. if your API level : 14 or Higher
If the API level is 14 or higher, you can use hasPermanentMenuKey().
Hope it will some how help you.
回答2:
This should work for all devices on the market:
public static boolean hasPermanentKeys(Activity activity) {
//
int height=0;
int realHeight=0;
WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
height = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
try {
realHeight = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
realHeight = realSize.y;
} catch (Exception ignored) {
}
if(height == realHeight){
return true;
}
else{
return false;
}
}
回答3:
although its an old post but if anyone comes across this here is a solution that could be used from support-v4 library (from library version 24.2.0 it will support upto API-9):
ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(context))
https://developer.android.com/topic/libraries/support-library/index.html
来源:https://stackoverflow.com/questions/14068138/alternate-to-haspermanentmenukey-for-android-2-3-3