碰到了需要获取状态栏高度的问题。
就像android后期版本,无法直接退出一样。找了一些方法来获取状态栏高度,结果都是为0.
还好,牛人是很多的,当时,找到一段代码,能够有效的获取状态栏的高度。特此记录,备忘,以及供大家参考。
public static int getHeight(Context context) {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 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());
sbar = context.getResources().getDimensionPixelSize(x);
return sbar;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
下面这个方法在 onCreate()方法中,获取高度为0
不在onCreate()方法中是有效的
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;