【发布时间】:2012-11-10 10:09:43
【问题描述】:
我试图在onCreate 中获取statusBar 高度,但我在这里找到的方法需要已经绘制了一些视图来获取它的大小,然后计算状态栏高度。
由于我在 onCreate 上,所以我还没有绘制任何东西来获得它的大小
有人可以帮我吗?
【问题讨论】:
我试图在onCreate 中获取statusBar 高度,但我在这里找到的方法需要已经绘制了一些视图来获取它的大小,然后计算状态栏高度。
由于我在 onCreate 上,所以我还没有绘制任何东西来获得它的大小
有人可以帮我吗?
【问题讨论】:
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);
}
});
【讨论】:
使用全局布局监听器
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);
}
});
【讨论】: