在开发全屏透明界面时,需要动态获取顶部状态栏的高度,具体方法如下:
/**
* 通过反射顶部状态栏的高度
*/
public static int getStatusBarHeight(Context context) {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0;
int top = 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());
top = context.getResources().getDimensionPixelSize(x);
sTopStatusHeight = top;
} catch (Exception e1) {
e1.printStackTrace();
}
return top;
}
通过反射获取状态栏高度,部分手机可能获取不到,这是就需要给一个大体的固定值如下:
public static void setStatusBarLocation(View ll_status_bar_location, Context context) {
ViewGroup.LayoutParams params = ll_status_bar_location.getLayoutParams();
if (DrawUtil.getStatusBarHeight(context) > 0) {
params.height = DrawUtil.getStatusBarHeight(context);
} else {
params.height = 75;
}
ll_status_bar_location.setLayoutParams(params);
}
其中ll_status_bar_location为占位的view