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

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值