Android判断设备是否有NavigationBar(虚拟按键)并获取它的高度

网上对于NavigationBar的判断有很多方法,但由于国内定制系统太多,导致兼容性不太好,这里提供一个实测兼容性比较好的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 判断是否有NavigationBar
*
* @param activity
* @return
*/
public static boolean checkHasNavigationBar(Activity activity) {
WindowManager windowManager = activity.getWindowManager();
Display d = windowManager.getDefaultDisplay();

DisplayMetrics realDisplayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
d.getRealMetrics(realDisplayMetrics);
}

int realHeight = realDisplayMetrics.heightPixels;
int realWidth = realDisplayMetrics.widthPixels;

DisplayMetrics displayMetrics = new DisplayMetrics();
d.getMetrics(displayMetrics);

int displayHeight = displayMetrics.heightPixels;
int displayWidth = displayMetrics.widthPixels;

return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
}

/**
* 获得NavigationBar的高度
*/
public static int getNavigationBarHeight(Activity activity) {
int result = 0;
Resources resources = activity.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0 && checkHasNavigationBar(activity)) {
result = resources.getDimensionPixelSize(resourceId);
}
return result;
}