有时候在计算屏幕可使用高度时 需要总像素减去statusbar的高度。
可以使用下面的方式指定系统中的的包名和dimen参数名获取。
private final static String STATUS_BAR_DEF_PACKAGE = "android";
private final static String STATUS_BAR_DEF_TYPE = "dimen";
private final static String STATUS_BAR_NAME = "status_bar_height";
int resourceId = getResources().getIdentifier(STATUS_BAR_NAME, STATUS_BAR_DEF_TYPE, STATUS_BAR_DEF_PACKAGE);
mStatusBarHeight = getResources().getDimensionPixelSize(resourceId);
Log.d(TAG, String.format("Get status bar height %d", mStatusBarHeight));
另外还可以通过反射的方式获取,但是要小心混淆。
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
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;
}