首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android IME 中獲取狀態欄高度:無 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;
}

適用場景

  • InputMethodService (IME) 無 Activity 引用
  • Dialog/PopupWindow 等非全屏上下文
  • 系統進程、壁紙服務等

原理說明

Android 系統在 frameworks/base/core/res/res/values/dimens.xml 定義了 <dimen name="status_bar_height">25dp</dimen>,通過資源 ID 反射獲取,無需 Window 對象。

備用方案(反射類)


public int getStatusBarHeightFallback() {
    try {
        Class c = Class.forName("com.android.internal.R$dimen");
        Object obj = c.newInstance();
        Field field = c.getField("status_bar_height");
        int x = Integer.parseInt(field.get(obj).toString());
        return getResources().getDimensionPixelSize(x);
    } catch (Exception e) {
        return 0; // 默認值
    }
}

緩存優化


private Integer cachedStatusBarHeight;

public int getStatusBarHeight() {
    if (cachedStatusBarHeight != null) return cachedStatusBarHeight;
    int h = getResources().getIdentifier("status_bar_height", "dimen", "android");
    cachedStatusBarHeight = (h > 0) ? getResources().getDimensionPixelSize(h) : 0;
    return cachedStatusBarHeight;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved