完美獲取Android狀態列高度

dj0379發表於2015-10-23

閒暇寫了個單本小說閱讀的應用。中間碰到了需要獲取狀態列高度的問題。

就像android後期版本,無法直接退出一樣。找了一些方法來獲取狀態列高度,結果都是為0.

還好,牛人是很多的,當時,找到一段程式碼,能夠有效的獲取狀態列的高度。特此記錄,備忘,以及供大家參考。

// 獲取系統狀態列高度
public int getSysBarHeight() {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0;
int sbar = 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());
sbar = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
Log.e("Jingle.du", "get status bar height fail");
e1.printStackTrace();
}
return sbar;
}

個人注:以下程式碼不能在onCreate裡面使用,否則獲取狀態列高度為0

Rect frame = new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight = frame.top;

相關文章