2012-11-10 56 views
1

我试图让statusBar高度在onCreate之内,但我在这里找到的方法需要一些视图已经绘制得到它的大小,然后计算statusBar高度。获取状态条onCreate()的高度

由于我上的onCreate,没有什么借鉴但对我来说,得到它的大小

有人能帮助我在这里?

回答

1

使用全局布局听众

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); 
    } 
}); 
+0

是否有任何其他的方式,我可以调用measure方法只有一次(在应用程序启动时) –

+0

将侦听器设置为我上面的,然后在onGlobalLayout()中将其删除!请尽量养成阅读Android文档的习惯。 http://developer.android.com/reference/android/view/ViewTreeObserver.html#removeOnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener) – Simon

+0

我编辑了我的回复。 – Simon

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