在画UI过程中,有些情况下需要知道statusBar高度:
网上有些方法是这样的:
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.v("@@@@@@", "the statusbar Height is : " + statusBarHeight);
类似:
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight;
Log.v("@@@@@@", "the titleBar Height is : " + titleBarHeight);
或者:
Rect rect = new Rect();
MainActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
View view = MainActivity.this.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
int topS = rect.top;//状态栏高度
int topT = rect.height() - view.getHeight();
Log.v("@@@@@@", "the statusbar Height is : " + topS);
Log.v("@@@@@@", "the titleBar Height is : " + topT);
在我的手机上,均不行。
后:
public static int getStatusBarHeight(Context context){
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 = context.getResources().getDimensionPixelSize(x);
Log.v("@@@@@@", "the status bar height is : " + statusBarHeight);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
经测试可行。
获取Android UI中statusBar高度的方法
本文介绍了一种在Android应用中获取statusBar高度的方法,包括使用Rect对象和通过反射获取status_bar_height属性,避免了传统的窗口可见显示区域方法在某些设备上的不准确性。
2225

被折叠的 条评论
为什么被折叠?



