android獲取狀態欄高度

在應用開發中,有時我們需要用代碼計算佈局的高度,可能需要減去狀態欄(status bar)的高度。狀態欄高度定義在系統尺寸資源中status_bar_height,但這並不是公開可直接使用的,例如像通常使用系統資源那樣Android.R.dimen.status_bar_height。但是系統給我們提供了一個Resource類,通過這個類我們可以獲取資源文件。下邊是在Activity中獲取的方法

  1. <span style="font-family: Arial, Helvetica, sans-serif;">public int getStatusBarHeight() {</span>  
  1.   int result = 0;  
  2.   int resourceId = getResources().getIdentifier("status_bar_height","dimen","android");  
  3.   if(resourceId > 0) {  
  4.       result = getResources().getDimensionPixelSize(resourceId);  
  5.   }  
  6.   return result;  
  7. }  


這裏還有另外一種方法,大家都知道Android的所有資源都會有惟一標識在R類中作爲引用。我們也可以通過反射獲取R類的實例域,代碼如下

  1. /** 
  2.  * 獲得狀態欄的高度 
  3.  * 
  4.  * @param context 
  5.  * @return 
  6.  */  
  7. public static int getStatusHeight(Context context) {  
  8.    
  9.     int statusHeight = -1;  
  10.     try{  
  11.         Class<!--?--> clazz = Class.forName("com.android.internal.R$dimen");  
  12.         Object object = clazz.newInstance();  
  13.         intheight = Integer.parseInt(clazz.getField("status_bar_height")  
  14.                 .get(object).toString());  
  15.         statusHeight = context.getResources().getDimensionPixelSize(height);  
  16.     }catch(Exception e) {  
  17.         e.printStackTrace();  
  18.     }  
  19.     return statusHeight;  
  20. }  




 
\

我們可以看到得到的結果是一樣的。當然,獲取狀態欄的高度方法是不是就只有以上兩種呢,當然不是,下邊再介紹一種獲取狀態欄高度的方法,不過不推薦使用,因爲這個方法依賴於WMS(窗口管理服務的回調)。

  1. Rect rectangle= newRect();  
  2. Window window= getWindow();  
  3. window.getDecorView().getWindowVisibleDisplayFrame(rectangle);  
  4. int statusBarHeight= rectangle.top; 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章