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

android 获取状态栏高度

2016-01-05 15:38 441 查看
需求描述

有时候计算view位置的时候需要得到状态栏的高度,然后减去这个高度,现在给大家总结两种获取状态栏高度的方法。

代码实现

方法一:

通过反射拿到R文件的dimen对象,然后直接拿到status_bar_height属性的值,也就是状态栏的高度

注意:这个方法是直接拿到系统的属性,不是通过计算,所以写在任何周期都OK

public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
Log.i("TAG", "statusHeight:" + statusHeight);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}


方法二:

拿到Window对象,然后测量出状态栏的高

注意:这种方法要等window启动才能测量,不然拿到的数值就是0,所以要等window完全启动才能调用

@Override
public void onWindowFocusChanged(boolean hasFocus) {
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.i("TAG", "statusBarHeight:" + statusBarHeight);
super.onWindowFocusChanged(hasFocus);
}


最后给大家分析下屏幕结构



屏幕区域大小的获取方法是,

Display defaultDisplay = this.getWindowManager().getDefaultDisplay();
int width = defaultDisplay.getWidth();// 屏幕的宽
int height = defaultDisplay.getHeight();// 屏幕的高

Point outP = new Point();
defaultDisplay.getSize(outP);
int width2 = outP.x;// 屏幕的宽
int height2 = outP.y;// 屏幕的高


应用区域的大小获取方法是

Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//应用区域离顶部距离,也就是状态栏的高
int statusBarHeight = frame.top;//同理也有left,right等
frame.width();//应用区域的宽
frame.height();//应用区域的高
Log.i("TAG", "statusBarHeight:" + statusBarHeight);


view绘制区域的大小获取方法

Rect outRect = new Rect();
this.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect);
int width3 = outRect.width();// view绘制区域的宽
int height3 = outRect.height();//view绘制区域的高


推理:状态栏的高为:屏幕区域的高减去应用区域的高,标题栏的高为:应用区域的高减去view绘制区域的高

注意:很多时候我们设置style为NOTITLEBAR,那么view绘制区域和应用区域重合,如果设置全屏,那么三个区域都重合。

建议用方法一,更方便快捷

/**

* --------------

* 欢迎转载 | 转载请注明

* --------------

* 如果对你有帮助,请点击|顶|

* --------------

* 请保持谦逊 | 你会走的更远

* --------------

* @author css

* @github https://github.com/songsongbrother

* @blog http://blog.csdn.net/xiangxi101

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: