Sebastian
Sebastian

Reputation: 2956

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.

Upvotes: 2

Views: 4158

Answers (4)

Alessio
Alessio

Reputation: 3173

This is how I did it, say you have:

main/
  res/
    values/
      strings.xml
    values-es/
      strings.xml

where under main/values you have your default language (let's assume English), and under_main/values-es_ the Spanish translation of it. Now you want one of your flavor to default to Spanish instead of English, even when the user select US or UK locales:

main/
  res/
    values/
      strings.xml
    values-es/
      strings.xml
a_flavor/
  res/
    values/
      strings.xml    // <-- this is a symbolic link

so I introduced in the flavor a symbolic link strings.xml to point to the Spanish translation, overwriting the default file under values.

Symlink was created with a command like:

$ cd app/src/a_flavor/res/values
$ ln -s ../../../main/res/values-es/strings.xml strings.xml

Upvotes: 0

k4dima
k4dima

Reputation: 6251

Use symlinks to different languages in flavour folders

Upvotes: -1

Sebastian
Sebastian

Reputation: 2956

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.

Upvotes: 1

MTZ4
MTZ4

Reputation: 2346

maybe you can try

public void setLocale(String lang) { 
    myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm);
    reloadUI(); // you may not need this, in my activity ui must be refreshed immediately so it has a function like this.
}

take from here

Upvotes: 1

Related Questions