Ivan Regados
Ivan Regados

Reputation: 61

get statusBar Height in onCreate()

I'm trying to get statusBar height inside onCreate but the methods that I found here need some view already draw to get it's size and then calculate statusBar height.

Since I'm on onCreate, there's nothing draw yet for me to get it's size

Someone can help me here?

Upvotes: 1

Views: 655

Answers (2)

Dory
Dory

Reputation: 7582

root = (ViewGroup)findViewById(R.id.root);
root.post(new Runnable() { 
public void run(){
    Rect rect = new Rect();
    Window win = getWindow();
    win.getDecorView().getWindowVisibleDisplayFrame(rect);
    int statusHeight = rect.top;
    int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
    int  titleHeight = contentViewTop - statusHeight;
    Log.e("dimen", "title = " + titleHeight + " status bar = " + statusHeight);
}
});

Upvotes: 2

Simon
Simon

Reputation: 14472

Use a global layout listener

public void onCreate(Bundle savedInstanceState)
{
     super.onCreate(savedInstanceState);

     // inflate your main layout here (use RelativeLayout or whatever your root ViewGroup type is
     LinearLayout mainLayout = (LinearLayout ) this.getLayoutInflater().inflate(R.layout.main, null); 

     // set a global layout listener which will be called when the layout pass is completed and the view is drawn
     mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
     new ViewTreeObserver.OnGlobalLayoutListener() {
          public void onGlobalLayout() {
               // measure your views here
          }
     }
 );

 setContentView(mainLayout);

[EDIT]

To do this only once:

ViewTreeObserver observer = mainLayout.getViewTreeObserver();

observer.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {
@Override
public void onGlobalLayout() {
    // measure your views here
    mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
   }
 });

Upvotes: 0

Related Questions