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

屏幕底部的黑色导航栏无法在Android中轻松移除。从3.0开始,它已成为Android的一部分,以替代硬件按钮。这是一张图片:


http://img4.mukewang.com/5da57d00000193a108000086.jpg

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


回首忆惘然
浏览 901回答 4
4回答

墨色风雨

试试下面的代码:Resources resources = context.getResources();int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");if (resourceId > 0) {    return resources.getDimensionPixelSize(resourceId);}return 0;

泛舟湖上清波郎朗

NavigationBar的高度对于某些设备有所不同,但对于某些方向也有所不同。首先,你必须检查设备是否有一个导航栏,那么如果该设备是平板电脑或不片剂(手机),最后你得看设备的方向,以获得正确的高度。public int getNavBarHeight(Context c) {         int result = 0;         boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();         boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);         if(!hasMenuKey && !hasBackKey) {             //The device has a navigation bar             Resources resources = c.getResources();             int orientation = resources.getConfiguration().orientation;             int resourceId;             if (isTablet(c)){                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");             }  else {                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");                  }             if (resourceId > 0) {                 return resources.getDimensionPixelSize(resourceId);             }         }         return result;} private boolean isTablet(Context c) {    return (c.getResources().getConfiguration().screenLayout            & Configuration.SCREENLAYOUT_SIZE_MASK)            >= Configuration.SCREENLAYOUT_SIZE_LARGE;}

慕婉清6462132

实际上,平板电脑(至少是Nexus 7)上的导航栏在纵向和横向上都有不同的尺寸,因此此功能应如下所示:private int getNavigationBarHeight(Context context, int orientation) {    Resources resources = context.getResources();    int id = resources.getIdentifier(            orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",            "dimen", "android");    if (id > 0) {        return resources.getDimensionPixelSize(id);    }    return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP