如何以编程方式获取 Android 导航栏的高度和宽度?

新手上路,请多包涵

屏幕底部的黑色导航栏在 Android 中不易移除。自 3.0 以来,它一直是 Android 的一部分,作为硬件按钮的替代品。这是一张图片:

系统栏

如何获取此 UI 元素的宽度和高度(以像素为单位)?

原文由 Kevik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 466
2 个回答

试试下面的代码:

 Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
    return resources.getDimensionPixelSize(resourceId);
}
return 0;

原文由 Sanket 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 Android R (SDK 30+),您可以使用此代码获取状态栏和导航栏的大小

WindowInsets insets = activity.getWindowManager().getCurrentWindowMetrics().getWindowInsets();
int statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top; //in pixels
int navigationBarHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom; //in pixels

原文由 tuantv.dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题