得到Android狀態列高度
阿新 • • 發佈:2019-01-25
推薦用法:
在應用開發中,有時我們需要用程式碼計算佈局的高度,可能需要減去狀態列(status bar)的高度。狀態列高度定義在Android系統尺寸資源中status_bar_height,但這並不是公開可直接使用的,例如像通常使用系統資源那樣android.R.dimen.status_bar_height。但是系統給我們提供了一個Resource類,通過這個類我們可以獲取資原始檔。下邊是在Activity中獲取的方法:
public int getStatusBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; }
以下是其它用法:
通過反射獲取R類的例項域,程式碼如下:
/** * 獲得狀態列的高度 * * @param context * @return */ public static int getStatusHeight(Context context) { int statusHeight = -1; try { Class<!--?--> clazz = Class.forName("com.android.internal.R$dimen"); Object object = clazz.newInstance(); int height = Integer.parseInt(clazz.getField("status_bar_height") .get(object).toString()); statusHeight = context.getResources().getDimensionPixelSize(height); } catch (Exception e) { e.printStackTrace(); } return statusHeight; }
不推薦用法:
依賴於WMS(視窗管理服務的回撥)。
Rect rectangle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight= rectangle.top;