Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
首先是這個api,但是這個方法有個局限性,在onCreate()以及到onResume()的生命周期里面執(zhí)行的話,獲取的高度為0,因為這個decorView的繪制需要時間,所以我們需要延時使用該方法來獲取高度;
new Runnable(){
@Override
public void run(){
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
}
}
然后可以用handler.postDelayed(run,200)去執(zhí)行,就能獲得statusBar的高度了,這個200毫秒其實應(yīng)該是大大超過了decorView的繪制時間了,因為View的繪制時間超過了16.7ms就會出現(xiàn)卡頓的現(xiàn)象,人眼來識別的話,每秒需要達到60幀,畫面才會流暢。但是,經(jīng)過測試,100毫秒左右是沒問題的。這個怎么會要這么久的時間去繪制,不是很懂
我們應(yīng)該使用一個在任何時候都能正常獲取到statusBar高度的方法,這樣應(yīng)用才不會出一些奇奇怪怪的問題。
Resources resources = getResources();
int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
int height = resources.getDimensionPixelSize(resourceId);
這個api在任何時候都能正常獲取到高度,其實是調(diào)用native方法。還有一種是用java的反射來獲取高度的:
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);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
這個方法沒有試過,看上去和第二個方法很像,獲取的包名,類名和字段名都一模一樣。
2016年4月22日