Android 获取StatusBar和NavigationBar的高度

在Activity中

int getStatusBarHeight {
    Rect frame = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    return frame.top;
}

在View中

int getStatusBarHeight {
    Rect frame = new Rect();
    (Activity(mContext)).getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    return frame.top;
}

这种基于Window的方法可能不适用对话框窗口。

还有一种简单直接的方法:

 private int getStatusBarHeight() {
       return mContext.getResources().getDimensionPixelSize(
              com.android.internal.R.dimen.status_bar_height);
 }

或者:

static final int mStatusBarHeight = (int) Resources.getSystem().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
static final int mNavigationBarHeight = (int) Resources.getSystem().getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);                                                                                                   

使用反射

        Class c;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int dim = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(dim);
        } catch (Exception e) {
            e.printStackTrace();
        }