配置`locale`变量已弃用 - Android

MBH*_*MBH 21 android

我使用此代码在多种语言app中手动设置默认语言:

public static void setLanguage(Context context, String languageCode){
    Locale locale = new Locale(languageCode);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;  // Deprecated !!
    context.getApplicationContext().getResources().updateConfiguration(config,
            context.getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)

所以现在我们不能通过config.locale设置语言环境,因为该变量将在API 24中删除.

所以我看到另一种方法是设置:

config.setLocales();

现场

在API级别1中添加

区域设置

此字段在API级别24中已弃用.请勿直接设置或读取此字段.使用getLocales()和setLocales(LocaleList).如果只需要主要语言环境,则getLocales().get(0)现在是首选访问者.

区域设置的当前用户首选项,对应于区域设置资源限定符.

我也注意到,setLocale(Locale)但是对于api 17及以上也是如此

我检查了setLocales(LocalList)文档,它以灰色标记,好像它也被弃用了!

那么什么可以解决这个问题!

Bas*_*jan 30

希望这有帮助,我还添加了吸气剂.

@SuppressWarnings("deprecation")
public Locale getSystemLocaleLegacy(Configuration config){
    return config.locale;
}

@TargetApi(Build.VERSION_CODES.N)
public Locale getSystemLocale(Configuration config){
    return config.getLocales().get(0);
}

@SuppressWarnings("deprecation")
public void setSystemLocaleLegacy(Configuration config, Locale locale){
    config.locale = locale;
}

@TargetApi(Build.VERSION_CODES.N)
public void setSystemLocale(Configuration config, Locale locale){
    config.setLocale(locale);
}

public static void setLanguage(Context context, String languageCode){
    Locale locale = new Locale(languageCode);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setSystemLocale(config, locale);
    }else{
        setSystemLocaleLegacy(config, locale);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        context.getApplicationContext().getResources().updateConfiguration(config,
            context.getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)

2016年12月3日更新

由于context.getApplicationContext().getResources().updateConfiguration()现已弃用,我强烈建议您查看此解决方案并采用不同的方法来覆盖Android系统配置.

更好的解决方案: https ://stackoverflow.com/a/40704077/2199894

  • 嘿,我真的很喜欢你的回答,但你发布了一个更好的解决方案的链接,你能简单解释一下为什么更好吗?如果我没有记错的话,“更好的解决方案”建议在每个活动中运行那段代码,如果可能的话,我宁愿避免这种情况,即使我有一个 BaseActivity...提前致谢! (2认同)