Reliably get height of status bar to solve KitKat translucent navigation issue

江枫思渺然 提交于 2019-11-28 19:13:49
public int getStatusBarHeight() {
      int result = 0;
      int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
      if (resourceId > 0) {
          result = getResources().getDimensionPixelSize(resourceId);
      }
      return result;
}

Use the above code in the onCreate method. Put it in a contextWrapper class. http://mrtn.me/blog/2012/03/17/get-the-height-of-the-status-bar-in-android/

Since api 21 there is official method for retrieving insets for status bar and navigation bar height when is translucent

ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
            final int statusBar = insets.getSystemWindowInsetTop();
            final int navigationBar = insets.getSystemWindowInsetBottom();
            return insets;
        }
    });

The height of the bottom Navigation bar is 48dp (in both portrait and landscape mode) and is 42dp when the bar is placed vertically.

Hope this helps.

The accepted answer always returns the status bar height (and in a somewhat hacky way). But some activities may actually be fullscreen, and this method doesn't differentiate between them.

This method works perfectly for me to find the status bar height relative to the current activity (place it in your Activity class, and use it once layout has finished):

public int getStatusBarHeight() {
    Rect displayRect = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(displayRect);
    return displayRect.top;
}

Note you could also just use displayRect directly in case you have other "window decorations" at the bottom or potentially even the sides of the screen.

recommend to use this script to get the status bar height

Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight = rectangle.top;
int contentViewTop = 
    window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;

   Log.i("*** Elenasys :: ", "StatusBar Height= " + statusBarHeight + " , TitleBar Height = " + titleBarHeight); 

(old Method) to get the Height of the status bar on the onCreate() method of your Activity, use this method:

public int getStatusBarHeight() { 
      int result = 0;
      int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
      if (resourceId > 0) {
          result = getResources().getDimensionPixelSize(resourceId);
      } 
      return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!