尊重原創、尊重作者,轉載請標明出處:
http://blog.csdn.net/lnb333666/article/details/41821149
目前也沒有可靠的方法來檢查設備上是否有導航欄。可以使用KeyCharacterMap.deviceHasKey來檢查設備上是否有某些物理鍵,比如說菜單鍵、返回鍵、Home鍵。然后我們可以通過存在物理鍵與否來判斷是否有NavigationBar(一般來說手機上物理鍵、NavigationBar共存).
- public static int getNavigationBarHeight(Activity activity) {
- Resources resources = activity.getResources();
- int resourceId = resources.getIdentifier("navigation_bar_height",
- "dimen", "android");
- //獲取NavigationBar的高度
- int height = resources.getDimensionPixelSize(resourceId);
- return height;
- }
上面這段代碼,在絕大多數情況下都能獲取到NavigationBar的高度。所以有人想通過這個高度來判斷是否有NavigationBar 是不行的。當然4.0版本以下就不用說了。確認個問題,NavigationBar是4.0以上才有么?
因為設備有物理鍵仍然可以有一個導航欄。任何設備運行自定義rom時都會設置一個選項,是否禁用的物理鍵,並添加一個導航欄。看看API:
ViewConfiguration.get(Context context).hasPermanentMenuKey() 有這么一句描述 :Report if the device has a permanent menu key available to the user(報告如果設備有一個永久的菜單主要提供給用戶).
android.view.KeyCharacterMap.deviceHasKey(int keyCode) 的描述:Queries the framework about whether any physical keys exist on the any keyboard attached to the device that are capable of producing the given key code(查詢框架是否存在任何物理鍵盤的任何鍵盤連接到設備生產給出關鍵代碼的能力。).
那么解決的辦法就是:
- @SuppressLint("NewApi")
- public static boolean checkDeviceHasNavigationBar(Context activity) {
- //通過判斷設備是否有返回鍵、菜單鍵(不是虛擬鍵,是手機屏幕外的按鍵)來確定是否有navigation bar
- boolean hasMenuKey = ViewConfiguration.get(activity)
- .hasPermanentMenuKey();
- boolean hasBackKey = KeyCharacterMap
- .deviceHasKey(KeyEvent.KEYCODE_BACK);
- if (!hasMenuKey && !hasBackKey) {
- // 做任何你需要做的,這個設備有一個導航欄
- return true;
- }
- return false;
- }