Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 獲取狀態欄高度的方法

編輯:關於 Android 程式設計

在實際開發中,我們偶爾需要用程式碼計算布局高度,這時往往需要扣除狀態欄(status bar)的高度。狀態欄高度其實定義在系統尺寸資源 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;
}

還有一種思路:Android 的所有資源都會在 R 類中擁有唯一標識以供引用,因此我們也可以透過反射來取得 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;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved