您的位置:首页 > 移动开发 > Android开发

Android如何判断NavigationBar是否显示(获取屏幕真实的高度)

2017-05-09 16:59 666 查看
转自:http://www.jianshu.com/p/84d951b3f079 简书-十个雨点

有些时候,我们需要知道当前手机上是否显示了NavigationBar,也就是屏幕底部的虚拟按键。

比如截屏的时候,要获取屏幕的高度,必须包括NavigationBar的高度。

试过网上的多种方法,但是对那种可以通过手势来显示/隐藏的NavigationBar没办法,最后终于找到了一个好办法,看代码:
public boolean isNavigationBarShow(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
Point realSize = new Point();
display.getSize(size);
display.getRealSize(realSize);
return realSize.y!=size.y;
}else {
boolean menu = ViewConfiguration.get(this).hasPermanentMenuKey();
boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if(menu || back) {
return false;
}else {
return true;
}
}
}

public static int getNavigationBarHeight(Activity activity) {
if (!isNavigationBarShow(activity)){
return 0;
}
Resources resources = activity.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height",
"dimen", "android");
//获取NavigationBar的高度
int height = resources.getDimensionPixelSize(resourceId);
return height;
}

public static int getSceenHeight(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getHeight()+getNavigationBarHeight(activity);
}

......我简直烦死华为了......

还有个补充:我判断NavigationBar的高度是为了让软键盘不遮挡输入框,要获得状态栏的高度和导航栏的高度,要用到 可视高度 减 状态栏 减 导航栏
private void initLayout() {
final int statusBarHeight = StatusBarUtil.getStatusBarHeight(getContext());//状态栏
//        final int navigationBarHeight = StatusBarUtil.getNavigationBarHeight(getContext());//导航栏
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
boolean showInput = false;

@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);//可视区域
int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) {
if (!showInput) {
showInput = true;
}
int navigationBarHeight = StatusBarUtil.getNavigationBarHeight(getActivity());//导航栏
if (rootView.getPaddingBottom() != heightDiff - statusBarHeight - navigationBarHeight) {
if (navigationBarHeight == 0 && r.top == 0){
rootView.setPadding(0, 0, 0, heightDiff);
}else {
rootView.setPadding(0, 0, 0, heightDiff  - statusBarHeight - navigationBarHeight);
}

}
} else {
if (!showInput) {
return;
}
showInput = false;
if (rootView.getPaddingBottom() != 0) {
rootView.setPadding(0, 0, 0, 0);
}
}
}
});
}
这里三星就很讨厌了,他的沉浸式状态栏不高度被抹掉了,不算进整个高度,所以rect.top = 0; 知道这点是因为站在大神的肩膀上:http://www.cnblogs.com/android-joker/p/4414682.html
以上~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NavigationBar
相关文章推荐