IneptusMechanicus
IneptusMechanicus

Reputation: 508

Xamarin Android change languagee folder on button click

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.

Upvotes: 1

Views: 494

Answers (1)

YumeYume
YumeYume

Reputation: 991

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.

Upvotes: 2

Related Questions