我试图在statusBar
内获得onCreate
高度,但我在这里找到的方法需要一些视图已经绘制以获得它的大小然后计算statusBar高度。< / p>
因为我在onCreate上,所以还没有什么可以让我获得它的大小
有人可以帮我吗?
答案 0 :(得分: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);
}
});
答案 1 :(得分: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);
}
});