android顶部状态栏 获取的两种方式

一般情况下我们通过调用下面方法即可获得状态栏的高度,同理也可以获得底部虚拟键盘的高度

/** * 获取状态栏高度 * * @return */public int getStatusBarHeight() {    //    Rect rect = new Rect();    getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);    int statusBarHeight = rect.top; // 状态栏高度    int bottomHeight = rect.bottom;// 底部虚拟键盘的    Log.i("statusBarHeight=", "statusBarHeight=" + statusBarHeight            + "---bottomHeight=" + bottomHeight);    return statusBarHeight;}

通过反射的形式获取状态栏高度,在oncreate中调用依然可以获得正确的高度

但是该方法如果在oncreate中调用获得状态栏高度为0,这是由于当前页面还未生成,所以上述方法使用情景只能在当页面已经加载完毕OnResume,类似 当按钮响应点击事件时获取状态栏高度;如果在oncreate调用就需要使用另外一种方式,通过反射的形式获取状态栏高度,在oncreate中调用依然可以获得正确的高度

/** * 获取状态栏高度 * * @return */public int getStatusBarHeight() {    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 = getResources().getDimensionPixelSize(x);    } catch (Exception e1) {        e1.printStackTrace();    }    return statusBarHeight;}

更多相关文章

  1. 修改android项目sdk版本的方法
  2. Android,TextView的所有属性和方法
  3. Android Studio Error 安装后Gradle:resolve dependencies:'clas
  4. TabHost 置于底部 顶部的方法
  5. Android启动模拟器出现:Failed to allocate memory: 8的解决方法
  6. eclipse添加android插件错误处理方法
  7. ReactNative 在用react-navigation组件时,没有 navigator.getCurr

随机推荐

  1. 为什么我的变量在TCPDF中没有定义?
  2. 加入vs多个数据副本:性能
  3. 这是什么原因啊,没有找出错来啊(数据库用的
  4. mysql - 如果“a”==“b”回显“折扣”
  5. Windows下 MySQL更新密码
  6. Python:我如何从datetime.timedelta对象中
  7. Mysql 批量修改字段存储过程
  8. mysql连接数设置操作(Too many connection
  9. 如何以分布式方式将Zend_cache与memcache
  10. MySQL服务无法启动,1067