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

Android 無 Context 獲取字符串資源:Resources.getSystem() 僅限系統資源

     編輯:程式設計綜合問答

普通類中無 `Context` 獲取 `R.string.xxx`,兩種場景:

1. 訪問應用自身資源 (R.string.app_defined)

  • **必須持有 Context** — 無捷徑。方案:
    • 構造函數/方法參數傳入 `Context`。
    • 自定義 `Application` 類持有靜態 `getContext()` (僅限進程內)。
    • 依賴注入 (Hilt/Koin) 注入 `Context`。
  • 錯誤嘗試:`Resources.getSystem().getString(R.string.my_str)` → **崩潰**,系統資源不含應用資源。

2. 訪問系統內置資源 (android.R.string.xxx)

  • 可用 `Resources.getSystem().getString(android.R.string.ok)` — 無需 Context。
  • 系統資源包含:標準按鈕文本 (OK/Cancel/Yes/No)、錯誤提示、日期時間格式等。

最佳實踐

// 工具類示例
public class StringUtils {
    public static String getString(@NonNull Context context, @StringRes int resId) {
        return context.getResources().getString(resId);
    }
    
    public static String getSystemString(@StringRes int systemResId) {
        return Resources.getSystem().getString(systemResId);
    }
}

結論:**應用資源必需 Context,系統資源可用 Resources.getSystem()**,切勿混淆。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved