获取Android系统状态栏的高度
方法一
状态栏高度定义在Android系统尺寸资源中status_bar_height,系统给我们提供了一个Resource类,通过这个类我们可以获取资源文件
public int getStatusBarHeight() {
//需要在Activity中执行
int height = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
height = getResources().getDimensionPixelSize(resourceId);
}
return height ;
}
方法二
因为Android的所有资源都会有惟一标识在R类中作为引用。我们也可以通过反射获取R类的实例域
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
方法三
依赖于WMS(窗口管理服务)的回调
Rect rectangle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight= rectangle.top;