Size of android notification bar and title bar?

Viewed 48708

Is there a way to obtain the size of the notification bar and title bar in android? At the moment I obtain the display width and height with:

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

After that I want to subtract the sizes of the bars so that I can stretch a video without losing aspect ratio. Currently I hide the bars because I can't see a better way.

8 Answers

I use the following code for getting heights:

For Status (Notification) bar:

View decorView = getWindow().getDecorView();
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;

For Title bar:

View contentView = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
int[] location = new int[2];
contentView.getLocationInWindow(location);
int titleBarHeight = location[1] - statusBarHeight;

This works waaaay better than hardcoding values because android will still return the value that would be the height of the status bar or action bar on that particular device even though they may not be visible.

So, the idea is to get the content view onto which all of your views are added.

public View getContentView(Activity a) {
        int id = a.getResources().getIdentifier("content", "id", "android");
        return a.findViewById(id);
    }

Then, in your activity

View cView = getContentView(this);
cView.post(()->{ 
int offsetY = cView.getTop(); 
// do whatever here.
});

The good thing with the above code is that it'll also account for the action bar.

Related