Android 檢查設備是否存在 導航欄 NavigationBar


尊重原創、尊重作者,轉載請標明出處:

http://blog.csdn.net/lnb333666/article/details/41821149

 

目前也沒有可靠的方法來檢查設備上是否有導航欄。可以使用KeyCharacterMap.deviceHasKey來檢查設備上是否有某些物理鍵,比如說菜單鍵、返回鍵、Home鍵。然后我們可以通過存在物理鍵與否來判斷是否有NavigationBar(一般來說手機上物理鍵、NavigationBar共存).

 

[java]  view plain copy print ? 在CODE上查看代碼片 派生到我的代碼片
 
  1. public static int getNavigationBarHeight(Activity activity) {  
  2.         Resources resources = activity.getResources();  
  3.         int resourceId = resources.getIdentifier("navigation_bar_height",  
  4.                 "dimen", "android");  
  5.         //獲取NavigationBar的高度  
  6.         int height = resources.getDimensionPixelSize(resourceId);  
  7.         return height;  
  8.     }  


上面這段代碼,在絕大多數情況下都能獲取到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(查詢框架是否存在任何物理鍵盤的任何鍵盤連接到設備生產給出關鍵代碼的能力。).

 

那么解決的辦法就是:

 

[java]  view plain copy print ? 在CODE上查看代碼片 派生到我的代碼片
 
    1. @SuppressLint("NewApi")   
    2.     public static boolean checkDeviceHasNavigationBar(Context activity) {  
    3.   
    4.         //通過判斷設備是否有返回鍵、菜單鍵(不是虛擬鍵,是手機屏幕外的按鍵)來確定是否有navigation bar  
    5.         boolean hasMenuKey = ViewConfiguration.get(activity)  
    6.                 .hasPermanentMenuKey();  
    7.         boolean hasBackKey = KeyCharacterMap  
    8.                 .deviceHasKey(KeyEvent.KEYCODE_BACK);  
    9.   
    10.         if (!hasMenuKey && !hasBackKey) {  
    11.             // 做任何你需要做的,這個設備有一個導航欄  
    12.             return true;  
    13.         }  
    14.         return false;  
    15.     }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM