Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration `locale` variable is deprecated - Android

Tags:

android

I use this code to set the default language manually in multiple languages 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()); } 

so now we cant set locale by config.locale is deprecated because the variable is going to be removed in API 24.

So i saw that the alternative is to set:

config.setLocales();

locale

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.

I noticed also that there is setLocale(Locale) as well but for api 17 and above

I checked the setLocales(LocalList) documentation and it is marked in grey as if it is also deprecated !

so what can be solution for this !?

like image 770
MBH Avatar asked Sep 20 '16 09:09

MBH


Video Answer


1 Answers

Hope this helps, I also added the getters.

@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()); } 

UPDATE 12/3/2016

Since context.getApplicationContext().getResources().updateConfiguration() is now deprecated, I highly recommend that you check out this solution and adopt a different approach to overwriting Android system configuration.

Better Solution: https://stackoverflow.com/a/40704077/2199894

like image 115
Bassel Mourjan Avatar answered Sep 21 '22 15:09

Bassel Mourjan