How Get height of the Status Bar and Soft Key Buttons Bar?

Joske369 picture Joske369 · Apr 1, 2015 · Viewed 29.1k times · Source

Is there a way in Android to get the size of the soft buttons bar and status bar togheter? or a way to go get the screen height without the height of both these bars? (they are not always the same, look at the nexus 7 for example)

Answer

Adrian Cid Almaguer picture Adrian Cid Almaguer · Apr 1, 2015

Height of the Status Bar

The height of the status bar depends on the screen size, for example in a device with 240 X 320 screen size the status bar height is 20px, for a device with 320 X 480 screen size the status bar height is 25px, for a device with 480 x 800 the status bar height must be 38px

so I 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("*** Value :: ", "StatusBar Height= " + statusBarHeight + " , TitleBar Height = " + titleBarHeight); 

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;
} 

Soft Key Buttons Bar

This method is very useful in order to set the layout padding in Android KitKat (4.4). Using this, you can avoid the soft buttons bar overlapping over your layout.

The getRealMetrics method is only available with API 17 and +

@SuppressLint("NewApi")
private int getSoftButtonsBarHeight() {
    // getRealMetrics is only available with API 17 and +
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight)
            return realHeight - usableHeight;
        else
            return 0;
    }
    return 0;
}

Reference:

Height of status bar in Android

Dimension of soft buttons bar