Android获取状态栏高度

来源:互联网 发布:联迪a8安装软件 编辑:程序博客网 时间:2024/05/17 04:59
获取状态栏高度有两种方法:
1.如果是在Activity中:
    Rect localRect = new Rect();      getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);      statusHeight = localRect.top;

限制:由于getWindow()方法在Activity中,所以只能在Activity中使用 ,当然了,如果你传递的context对象可以被强转成Activity,那也可以,如下:
((Activity)mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); 

如果不能强转,而又不在activity中,还可以利用反射机制获取,这种方法只要有context对象就可以使用:
private int getStatusBarHeight(Context context) {Class<?> c = null;          Object obj = null;          Field field = null;          int x = 0, 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 = context.getResources().getDimensionPixelSize(x);          } catch (Exception e1) {              e1.printStackTrace();          }          return statusBarHeight;}
0 0
原创粉丝点击