配置`locale`变量已被弃用 – 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());
}

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

所以我看到替代方法是设置:

config.setLocales();

现场

Added in API level 1

Locale locale

This field was deprecated in API
level 24. Do not set or read this directly. Use getLocales() and
setLocales(LocaleList). If only the primary locale is needed,
getLocales().get(0) is Now the preferred accessor.

Current user preference for the locale,corresponding to locale
resource qualifier.

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

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

所以可以解决这个问题!

解决方法

希望这有帮助,我也添加了吸气剂.
@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());
}

更新12/3/2016

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

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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...