需求
先说下要实现的功能
有NavigationBar 在上边显示,没有则全屏显示
思路
- 设置导航栏透明属性
- 判断是否有虚拟导航栏
- 计算导航栏的高度
编码
设置导航栏透明属性
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
判断是否有虚拟导航栏
(找了很多方案,没有比较有效的方案,这里我采用了分机型适配)
华为
private static boolean isSupportNavBar(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//noinspection ConstantConditions
Display display = wm.getDefaultDisplay();
Point size = new Point();
Point realSize = new Point();
display.getSize(size);
display.getRealSize(realSize);
return realSize.y != size.y || realSize.x != size.x;
}
boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
return !menu && !back;
}
小米
private static boolean isXiaoMiNavigationBarShow(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (Settings.Global.getInt(context.getContentResolver(), "force_fsg_nav_bar", 0) != 0) {
//开启手势,不显示虚拟键
return false;
}
}
return true;
}
vivo
private static boolean isVivoNavigationBarShow(Context context) {
int val = Settings.Secure.getInt(context.getContentResolver(), "navigation_gesture_on", 0);
return val != 0;
}
计算导航栏的高度
private static int getNavigationHeight(Context context) {
if (context == null) {
return 0;
}
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height",
"dimen", "android");
int height = 0;
if (resourceId > 0) {
//获取NavigationBar的高度
height = resources.getDimensionPixelSize(resourceId);
}
return height;
}