獲取statusBar(狀態(tài)欄)高度的幾個方法

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日

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容