1.传统方式:
|
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
|
在4.0.3之后获取出来值可能为0。解决方案如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public int getHeight(){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, height= DEFAULT_HEIGHT;
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());
height = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return height;
}
|
方法2:
|
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
|
仍然有可能获取为0,使用反射获取com.android.internal.R.dimen.status_bar_height的值:(Rom开发可以直接使用getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height)
)
|
class c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
int y = getResources().getDimensionPixelSize(x);
|
方法三:个人认为比较靠谱,除非google手贱把状态栏高度对应的名字的名字改了。
|
Resources.getSystem().getDimensionPixelSize(
Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));
|