1

我正在尝试获取statusBar内部高度,onCreate但我在这里找到的方法需要已经绘制了一些视图来获取它的大小,然后计算 statusBar 高度。

因为我在 onCreate 上,所以我还没有画出它的大小

有人可以在这里帮助我吗?

4

2 回答 2

2
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);
}
});
于 2013-09-21T07:09:31.230 回答
0

使用全局布局监听器

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

[编辑]

只需执行一次:

ViewTreeObserver observer = mainLayout.getViewTreeObserver();

observer.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {
@Override
public void onGlobalLayout() {
    // measure your views here
    mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
   }
 });
于 2012-11-10T10:56:46.450 回答