项目中用到了,网上找到一段代码,能够有效的获取状态栏的高度,记录备忘。
- /**
- * 获取状态栏高度
- *
- * @return
- */
- public int getStatusBarHeight()
- {
- Class<?> c = null;
- Object obj = null;
- java.lang.reflect.Field field = null;
- int x = 0;
- int 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);
- return statusBarHeight;
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return statusBarHeight;
- }
- 方法二:获取状态栏高度和标题栏高度:
- private void getBarHeight()
{
// 获取状态栏高度
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
statusBarHeight = frame.top;
int contenttop = this.getWindow()
.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// statusBarHeight是上面所求的状态栏的高度
titleBarHeight = contenttop - statusBarHeight;
Log.v(TAG, "statusBarHeight = " + statusBarHeight
+ ", titleBarHeight = " + titleBarHeight);
}