最近项目中使用相机预览,绘制了图层,由于不同手机的分辨率不同,导致了适配的问题。研究了网上很多的方法,最后终于找到了一个可以判断NavigationBar是不是显示的方法。
//判断是否存在NavigationBar
public static boolean hasNavigationBar(Context context) {
if (getStatusBarHeight(context) + getScreenHeight(context) < ScreenUtils.getScreenRealHeight(context)) {
return true;
} else {
return false;
}
}
public static int getStatusBarHeight(Context context) {
Resources rs = context.getResources();
int resourceId = rs.getIdentifier("status_bar_height", "dimen", "android");
int statusHeight = rs.getDimensionPixelSize(resourceId);
return statusHeight;
}
public static int getNavigationBarHeight(Context context) {
Resources rs = context.getResources();
int navId = rs.getIdentifier("navigation_bar_height", "dimen", "android");
int navHeight = rs.getDimensionPixelSize(navId);
return navHeight;
}
public static int getScreenRealHeight(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return getScreenHeight(context);
}
int orientation = context != null
? context.getResources().getConfiguration().orientation
: TiApp.getContext().getResources().getConfiguration().orientation;
orientation = orientation == Configuration.ORIENTATION_PORTRAIT ? PORTRAIT : LANDSCAPE;
if (mRealSizes[orientation] == null) {
WindowManager windowManager = context != null
? (WindowManager) context.getSystemService(Context.WINDOW_SERVICE)
: (WindowManager) TiApp.getContext().getSystemService(Context.WINDOW_SERVICE);
if (windowManager == null) {
return getScreenHeight(context);
}
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getRealSize(point);
mRealSizes[orientation] = point;
}
return mRealSizes[orientation].y;
}
public static int getScreenHeight(Context context) {
if (context != null) {
return context.getResources().getDisplayMetrics().heightPixels;
}
return 0;
}
原理就是根据ScreenHeight与StatusBarHeight来判断,两者之和大于等于ScreenRealHeight,就是不显示NavigationBar。
只有当ScreenHeight+StatusBarHeight < ScreenRealHeight,说明还有一部分没有显示,那就是NavigationBar的高度。
目前测试了华为手机,一切正常。也适用于 Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1,也就是SDK小于21的版本。
因为不存在虚拟NavigationBar,此时ScreenHeight=ScreenRealHeight。 所以ScreenHeight+StatusBarHeight > ScreenRealHeight。也就是一样都可以判断的。
还有其他的类型手机还没有测试,此方法仅供参考。