Galaxy S8:屏幕高度返回错误值

3

这是我们获取屏幕高度的方法:

getResources().getDisplayMetrics().heightPixels;

我们遇到的问题是,由于Galaxy S8的隐藏导航栏,返回的值是高度减去导航栏大小(即使用户隐藏了导航栏)。我们如何获取完整可用的高度?例如:屏幕高度为2220像素,但返回的值是2076。
答案需要能够在有或没有隐藏导航栏的Galaxy S8以及其他设备上使用。非常感谢您的帮助。
2个回答

2

尝试使用以下内容:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);
Point是来自android.graphics包的一个类。
根据文档:https://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point) 获取显示器的真实尺寸,不减去任何窗口装饰或应用任何兼容性比例因素。
该尺寸会根据显示器的当前旋转进行调整。
当窗口管理器使用adb shell wm size模拟较小的显示器时,实际尺寸可能比屏幕的物理尺寸小。
编辑:
我在LG G4上检查了这段代码,它可以正常工作。
//get the full height of device
      Point displaySize = new Point();
      getWindowManager().getDefaultDisplay().getRealSize(displaySize);

      Resources resources = getResources();
            int navBarId = resources.getIdentifier("navigation_bar_height", "dimen", "android");


          int fullHeight = displaySize.y;
//get nav bar size
          int navbarSize = resources.getDimensionPixelSize(navBarId);
          int availableSize = fullHeight;
//check is navbar is visible
          boolean navBarVisible = (getWindow().getDecorView().getSystemUiVisibility() &
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
          if(navBarVisible){
                    availableSize -= navbarSize;
                }

此外,您可以使用以下代码:
view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int i) {
                Log.d("Nav bar visible : ", String.valueOf((i & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)==0));
            }
        });

检查导航栏何时隐藏。


1
好的,请检查此链接:https://developer.android.com/reference/android/view/View.html#setSystemUiVisibility(int) 特别是这个方法: public void onSystemUiVisibilityChange(int visibility) - Maciej Białorucki
1
糟糕 :/,很抱歉我没有帮上忙 :( - Maciej Białorucki
1
很遗憾,@Ambi,目前还没有解决这个问题。唯一的好消息是,根据S8 Beta计划,这个问题似乎已经被修复了,所以只要更新到每个S8设备上,这个问题就不会再存在了。 - Psest328
1
@Ambi,在manifest文件中有一个标志可以设置,使您的应用程序不接受2:1的宽高比,并强制显示导航栏。我现在正在使用手机,无法发布链接,但很容易搜索到。那就是我最终选择的方式。一旦更新推送到所有设备,我将进行另一次更新,删除该标志。 - Psest328
1
@Aadithya 好消息:Galaxy S8 Oreo更新已经修复了该问题!坏消息:如果用户仍在使用Nougat,则没有“修复”选项。您必须尝试其中一种解决方法。第二个好消息:S8的Oreo更新已经全球推出,因此用户仍在使用nougat不应该再是一个问题了。 - Psest328
显示剩余12条评论

0

我曾经遇到过同样的问题,最终通过decorview解决了这个问题:

//Get the correct screen size even if the device has a hideable navigation bar (e.g. the Samsung Galaxy S8)
View decorView = getWindow().getDecorView(); //if you use this in a fragment, use getActivity before getWindow()
Rect r = new Rect();
decorView.getWindowVisibleDisplayFrame(r);
int screenHeight = r.bottom; // =2220 on S8 with hidden NavBar and =2076 with enabled NavBar
int screenWidth = r.right; // =1080 on S8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接