配置`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 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...