获得StatusBar的高度:
方法一:
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
但是此段代码不能直接放在onCreate方法或普通的线程中(否则得到的高度为0),可以放在View的post方法中,如下:
new View(this).post(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
System.out.println("statusBarHeight:" + statusBarHeight);
}
});
或者放在Activity的onWindowFocusChanged方法中
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
System.out.println("statusBarHeight:" + statusBarHeight);
}
方法二:
用反射
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0,statusBarHeight = 0;
try{
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = getResources().getDimensionPixelSize(x);
}catch(Exception e){
e.printStackTrace();
}
另外要注意的是,如果计算时状态栏已经被隐藏了,则得到的高度为负数,所以只有在状态栏被隐藏前才能计算其高度。