一、网上找了很多方法判断是否显示底部导航栏,但是都不准确
网上方法一
public boolean checkDeviceHasNavigationBar(Context context) {
boolean hasNavigationBar = false;
try {
Resources rs = context.getResources();
int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
if (id > 0) {
hasNavigationBar = rs.getBoolean(id);
}
Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
Method m = systemPropertiesClass.getMethod("get", String.class);
String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
if ("1".equals(navBarOverride)) {
hasNavigationBar = false;
} else if ("0".equals(navBarOverride)) {
hasNavigationBar = true;
}
} catch (Exception e) {
}
return hasNavigationBar;
}
网上方法二
public static boolean checkDeviceHasNavigationBar(Context context) {
boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(4);
return !hasMenuKey && !hasBackKey;
}
二、如何获取底部虚拟导航栏高度
public static int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return resourceId != 0 ? resources.getDimensionPixelSize(resourceId) : 0;
}
三、记录一个取巧的检测判断是否显示导航栏的方法,前面方法一、方法二获取都不准确。
先获取手机屏幕真实高度,然后获取屏幕展示高度,再获取底部导航栏高度,如果显示高度+底部导航栏高度 <= 屏幕真实高度, 说明显示虚拟底部导航栏,反之则不显示。经过测试是准确的
public boolean checkDeviceHasNavigationBar(Context context) {
WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display defaultDisplay = manager.getDefaultDisplay();
//屏幕实际高度
Point realPoint = new Point();
defaultDisplay.getRealSize(realPoint);
//屏幕显示高度
DisplayMetrics outMetrics = new DisplayMetrics();
defaultDisplay.getMetrics(outMetrics);
//虚拟底部导航高度
int navigationBarHeight = BarUtils.getNavigationBarHeight(context);
if ((outMetrics.heightPixels + navigationBarHeight) <= realPoint.y){
//如果显示高度+底部导航栏高度 <= 屏幕真实高度, 说明显示虚拟底部导航栏,反之则不显示
return true;
}
return false;
}
再提供一个正确获取是否显示底部导航栏方法
public static boolean checkDeviceHasNavigationBar(Context context) {
try {
if (context != null && context instanceof Activity) {
Activity activity = (Activity) context;
ViewGroup viewGroup = (ViewGroup) activity.getWindow().getDecorView();
if (viewGroup != null) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View childAt = viewGroup.getChildAt(i);
if (childAt != null && childAt.getId() != -1) {
String resourceEntryName = activity.getResources().getResourceEntryName(viewGroup.getChildAt(i).getId());
if (TextUtils.equals(resourceEntryName, NAVIGATION)) {
return true;
}
}
}
}
}
} catch (Exception e) {
}
return false;
}
网友评论