1

I'm working on a app in Xamarin.Android and it has to support English and Bulgarian. Most of the text is stored in the Strings.xml in the values folder. The English text is in the default values folder and the Bulgarian text is in values-bg. The filename for both is String.xml, and the name of each string is the same as it's translated version. Now how can I make it so that when i click one button it reads the strings from values-bg and when i click another it reads from the default again? Also I would like that to be so for every activity in the app.

1 Answers1

2

I've been testing how to change locale programmatically, and I finally found a solution that worked for me.

As you said, you need a values folder, containing strings.xml with default values, which would be english, then a values-bg folder, with the same file but with Bulgarian translated values. It is important that strings have the same name, so you did it right.

Then, in your click event, you can add this :

var locale = new Java.Util.Locale ("bg");
Android.Content.Res.Configuration conf = Resources.Configuration;
conf.Locale = locale;
DisplayMetrics dm = Resources.DisplayMetrics;
Resources.UpdateConfiguration (conf, dm);
Recreate ();

First, that code will declare a Locale variable for "bg" locale. Then, it gets the actual configuration of the device, and apply the new Locale to it. Using UpdateConfiguration, it save the changes. The Recreate is optional, it just, as its name explains it all, recreates the current activity, which will be loaded using the new configuration, with a locale "bg" instead of whatever default locale was applied. It will now fetch strings in the values-bg folder.

NOTE : I've read in the comments of the accepted answer here that on some devices, the configuration will reset to default after some time in the app. I'm not sure why this happens, but you might want to check if the locale has been changed somehow when loading a new activity, to prevent that rollback.

Community
  • 1
  • 1
YumeYume
  • 981
  • 2
  • 12
  • 33
  • Will this change the locale for the whole app, or just the current activity? – IneptusMechanicus Jul 22 '16 at 12:41
  • I'm not certain, but I'd say for the whole app. If you want that behavior only on one activity, you can create a method similar to the one in my answer but applying default locale instead of a new locale with "bg" attribute. – YumeYume Jul 22 '16 at 13:38
  • That's just it, I want it to work for the whole app. I haven't had a chance to try it yet, but I will give feedback ASAP and up the answer if it works. – IneptusMechanicus Jul 22 '16 at 21:18