您的位置:首页 > 移动开发 > Android开发

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

2015-10-25 17:16 513 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: