完美获取Android状态栏高度

来源:互联网 发布:sql分组查询所有数据 编辑:程序博客网 时间:2024/05/01 18:10

来自: http://www.cnblogs.com/LuoYer/archive/2011/11/06/2238167.html

闲暇写了个单本小说阅读的应用。中间碰到了需要获取状态栏高度的问题。

就像android后期版本,无法直接退出一样。找了一些方法来获取状态栏高度,结果都是为0.

还好,牛人是很多的,当时,找到一段代码,能够有效的获取状态栏的高度。特此记录,备忘,以及供大家参考。

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 = getResources().getDimensionPixelSize(x);
} catch(Exception e1) {
    loge("get status bar height fail");
    e1.printStackTrace();
}

个人注:以下代码不能在onCreate里面使用,否则获取状态栏高度为0

Rect frame = new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight = frame.top;

 

 

原创粉丝点击