Android获取状态栏高度

来源:互联网 发布:宣城超越时空网络会所 编辑:程序博客网 时间:2024/04/29 05:26

1.传统方式:

123
Rect frame = new Rect();   getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);   int statusBarHeight = frame.top;  

在4.0.3之后获取出来值可能为0。解决方案如下:

 1 2 3 4 5 6 7 8 91011121314151617
public int getHeight(){        Class<?> c = null;        Object obj = null;        Field field = null;        int x = 0, height= DEFAULT_HEIGHT;        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());            height = getResources().getDimensionPixelSize(x);        } catch (Exception e1) {            e1.printStackTrace();        }        return height;    }

方法2:

123
Rect frame = new Rect();   getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);   int statusBarHeight = frame.top;  

仍然有可能获取为0,使用反射获取com.android.internal.R.dimen.status_bar_height的值:(Rom开发可以直接使用getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height)

12345
class c = Class.forName("com.android.internal.R$dimen");Object obj = c.newInstance();Field field = c.getField("status_bar_height");int x = Integer.parseInt(field.get(obj).toString());int y = getResources().getDimensionPixelSize(x);

方法三:个人认为比较靠谱,除非google手贱把状态栏高度对应的名字的名字改了。

12
Resources.getSystem().getDimensionPixelSize(    Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));

0 0
原创粉丝点击