2012-11-10 92 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); 
} 
});