Wednesday, January 6, 2010

Getting Height of Status and Title Bar

Category: UI
Subcategory: Window/Layout Dimensions
Android Platform: 1.5, Google APIs 3
Referenced Classes: android.app.Activity, android.app.Dialog, android.view.View, android.view.Window
Additional Info: Vertical Orientation

In some cases, determining the height for both Status and Title Bar is necessary. Using Window.getDecorView().getWindowVisibleDisplayFrame(...), I was able to find the height for both:
code snippet
Rect rect= new Rect();
Window window= activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight= rect.top;
int contentViewTop=
window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;
Note, that decorView must be attached to the Window (i.e. Dialog showing), for getWindowVisibleDisplayFrame(...) to return coords properly, otherwise both rect.top and rect.left will be 0. Alternatively, any attached view from within the layout should suffice. Please, see my comments.

4 comments:

  1. It's really great to see this article!!
    But... it seem doesn't work for me...
    according to your code, both statusBarHeight and titleBarHeight get zero.
    Have any idea??

    Thanks a lot!!

    ReplyDelete
  2. Yes, I know why. The method View.getWindowVisibleDisplayFrame(...) will only return coords when the view is attached to a Window. Otherwise, it returns the raw display size, causing statusBarHeight to be 0. I called the above code from within a Dialog, hence, the decorView was attached to a Window. Try something like the following, assuming you are in Activity.onCreate(...), with a view from your layout (i.e. mapView):

    layoutView1.post(new Runnable()
    {
    public void run()
    {
    Rect rect= new Rect();
    Window window= getWindow(); layoutView1.getWindowVisibleDisplayFrame(rect);
    int statusBarHeight= rect.top;
    int contentViewTop= window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
    int titleBarHeight= contentViewTop - statusBarHeight;
    }
    });

    ReplyDelete
  3. This is grate idea : )
    Thank you,

    ReplyDelete