如何在 Android 中获取屏幕的可用高度?我需要高度减去状态栏/菜单栏或屏幕上可能出现的任何其他装饰,我需要它适用于所有设备。另外,我需要在 onCreate 函数中知道这一点。我知道以前有人问过这个问题,但我已经尝试过他们的解决方案,但都没有用。以下是我尝试过的一些方法:
这里不考虑状态栏/菜单栏:
Display display = getWindowManager().getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
这也不是:
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
也不是这个:
Point size = new Point();
getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
这不起作用:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
// since SDK_INT = 1;
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
try
{
// used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
screenWidth = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
screenHeight = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
}
catch (Exception ignored)
{
// Do nothing
}
try
{
// used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
screenWidth = realSize.x;
screenHeight = realSize.y;
}
catch (Exception ignored)
{
// Do nothing
}
然后我使用以下代码从屏幕高度中减去状态栏和菜单栏的高度:
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
result = getResources().getDimensionPixelSize(resourceId);
screenHeight -= result;
result = 0;
if (screenHeight >= screenWidth)
resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
else
resourceId = getResources().getIdentifier("navigation_bar_height_landscape", "dimen", "android");
if (resourceId > 0)
result = getResources().getDimensionPixelSize(resourceId);
screenHeight -= result;
在 API 17 上,它可以正确计算纵向状态栏和菜单栏的高度,但不能正确计算横向状态栏的高度。在 API 10 上,它返回 0。我需要它在所有设备或最低 API 10 上理想地工作。
最佳答案
您是否尝试过在 Activity 类的 onWindowFocusChanged 中计算高度?这通过计算您真正想要的东西来消除 API 的麻烦,而不是弄乱菜单栏等。
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
screenHeight=content.getHeight();
}
关于java - 我如何在 Android 中获取屏幕的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17101880/