User has a flag, from where he is from (1 - Slovenia, 2 - Croatia) and I want to change locale and app language based on this flag.
When I'm on login page, user can choose what language he wants by pressing on the flag (button text and labels are translated successfully when this flags are pressed).
Code for changing language on loging page (arg is si or hr (name for slovenian and croatian language)):
private void ExecuteOnLanguageSelectedCommand(string arg)
{
if (arg == null)
return;
DependencyService.Get<ILocalize>().SetLocale(new CultureInfo(arg));
...
On app load, I check if language is set in Application settings or secure storage, if neither, then I go with phone language. This also works as expected, language is changed.
public App()
{
InitializeComponent();
...
CultureInfo ci = null;
string localeFromSS = SecureStorage.GetAsync("locale").Result;
if (localeFromSS != null)
ci = new CultureInfo(localeFromSS);
else if (ApplicationSettings.Locale != null)
ci = new CultureInfo(ApplicationSettings.Locale);
else
ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
DependencyService.Get<ILocalize>().SetLocale(ci);
...
But when user logs in and I want to change app language based on his location, language doesn't change, it stays like it was before. I tried changing language in LoginViewModel inside and outside mainUI thread:
...
string locale = await SecureStorage.GetAsync("locale").ConfigureAwait(false);
DependencyService.Get<ILocalize>().SetLocale(new CultureInfo(locale));
Device.BeginInvokeOnMainThread(async () =>
{
// string locale = await SecureStorage.GetAsync("locale").ConfigureAwait(false);
// DependencyService.Get<ILocalize>().SetLocale(new CultureInfo(locale));
Application.Current.MainPage = new AppShell();
await Shell.Current.GoToAsync("//main").ConfigureAwait(false);
});
...
Tried calling it in auth manager where I get locale info, but nothing changes it.
But when app is closed and opened, so it hits App() in App.xaml.cs constructor it changes language, the strange thing is it works in LoginPage.
Also, this is how I'm rerouting user, when he logs in, if that might help you in some way:
public App()
{
...
var IsLoggedIn = SecureStorage.GetAsync("isLoggedIn").Result;
var HasReadPrivacy = SecureStorage.GetAsync("HasReadPrivacy").Result;
if (ApplicationSettings.HasConnectivity == false)
MainPage = new NoConnectionPage();
else if (IsLoggedIn == "1")
if (HasReadPrivacy == "1")
MainPage = new AppShell();
else
MainPage = new PrivacyPolicyPage();
else
MainPage = new LoginPage();
...
This is code in Android Localize class that I'm calling with dependancyService
public void SetLocale(CultureInfo ci)
{
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}