You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API≤32时无需Context如何获取Android应用Locale(适配独立语言)

在API ≤32设备上无Context获取应用Locale的解决方案

Android API 33引入了Per-app language preferences(应用级语言偏好),允许开发者独立于系统语言修改应用语言。为兼容API ≤32设备,Androidx AppCompat 1.6.0-beta01新增AppCompatDelegate.setApplicationLocales(appLocale);实现应用与系统语言分离,但API ≤32时Locale.getDefault()返回的是系统Locale,且需求是无需依赖Context获取当前应用Locale(排除存储方案,因存储需Context)。

可行方案:使用AppCompatDelegate静态方法获取

AppCompat 1.6.0-beta01及以上版本提供了静态方法AppCompatDelegate.getApplicationLocales(),无需Context即可获取当前设置的应用级Locale列表:

// 获取应用Locale列表
LocaleListCompat appLocales = AppCompatDelegate.getApplicationLocales();
Locale currentAppLocale;

if (!appLocales.isEmpty()) {
    // 取第一个设置的Locale作为应用当前Locale
    currentAppLocale = appLocales.get(0);
} else {
    // 未主动设置过应用Locale时,回退到系统默认Locale
    currentAppLocale = Locale.getDefault();
}

关键说明

  • 该方法跨API版本通用,无论API ≤32还是API 33+,都能正确返回通过AppCompatDelegate.setApplicationLocales()设置的应用Locale
  • 若未主动设置过应用Locale,getApplicationLocales()会返回空列表,此时可回退到Locale.getDefault()获取系统Locale
  • 需确保项目依赖的AppCompat库版本≥1.6.0-beta01

内容的提问来源于stack exchange,提问作者Mohd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:58:58