Andorid获取状态栏高度

来源:互联网 发布:opencv java 图片人脸 编辑:程序博客网 时间:2024/05/08 00:19

android开发中避免不了的要计算状态栏高度,其高度是定义在Android系统尺寸资源中status_bar_height,但是不能公开使用。android提供了Resourse类获取资源文件:

publicintgetStatusBarHeight() {
  intresult = 0;
  intresourceId = getResources().getIdentifier("status_bar_height","dimen","android");
  if(resourceId > 0) {
      result = getResources().getDimensionPixelSize(resourceId);
  }
  returnresult;
}
这里还有另外一种方法,大家都知道Android的所有资源都会有惟一标识在R类中作为引用。我们也可以通过反射获取R类的实例域,代码如下:

/**
 * 获得状态栏的高度
 *
 * @param context
 * @return
 */
publicstaticint getStatusHeight(Context context) {
 
    intstatusHeight = -1;
    try{
        Class<!--?--> clazz = Class.forName("com.android.internal.R$dimen");
        Object object = clazz.newInstance();
        intheight = Integer.parseInt(clazz.getField("status_bar_height")
                .get(object).toString());
        statusHeight = context.getResources().getDimensionPixelSize(height);
    }catch(Exception e) {
        e.printStackTrace();
    }
    returnstatusHeight;
}

0 0
原创粉丝点击