NoActivity.java NoActivity.java - 3 months ago 8
Android Question

Changing app's default language for a specific flavor

I'm looking for a way to "swap" the default language with the secondary language that are already defined by the string.xml files in the main project. This should only affect a specific flavor.

Example situation: An app's flavor is targeted to a different region than all other flavors, where the default language does not make sense for users anymore.

Note: Copy-Pasting the string files from the main project is not a solution.

Answer

The solution I went for, based on MTZ4's solution, was calling this on onCreate() in my application's singleton:

 /**
  * Sets the locale to {@link Locale#ENGLISH}
  * if the device locale is not {@link Locale#GERMAN}.
  */
 public void setLocale() {
     if(BuildConfig.FLAVOR.equals("flavorWithSwapedLocale")) {
         Resources res = getResources();
         Configuration conf = res.getConfiguration();
         if (!conf.locale.equals(Locale.GERMAN)) {
             conf.locale = Locale.ENGLISH;
             res.updateConfiguration(conf, res.getDisplayMetrics());
         }
     }
 }

Note that the default language in the main project is German, this swap makes the default flavor language English, unless the device is in German.

With this approach, an app restart might be needed for the changes to show after changing the device's language.

Comments