I'm developing a crossplatform app using Xamarin Forms, primary target Android.
The app I'm working on refers to .resx files for languages.
The translations works fine as the phone is set to different langauges.
How can I switch languages from the app settings at runtime on the fly?
I tried using DependencyService to call a function on Android side, but, despite returning with no error, it doesn't change the language.
C# project
bool test = DependencyService.Get<ILanguageService>().SetLanguage(selectedLang.StringValue);
Android Project
[assembly: Dependency(typeof(LanguageService))]
namespace MyLangApp.Droid.Service
{
public class LanguageService:ILanguageService
{
public bool SetLanguage(string lang = "")
{
try
{
Locale locale = string.IsNullOrEmpty(lang) ? new Locale("en-US") : new Locale(lang);
Locale.Default = locale;
var config = new Android.Content.Res.Configuration();
config.Locale = locale;
var context = Android.App.Application.Context;
context.Resources.UpdateConfiguration(config, context.Resources.DisplayMetrics);
return true;
}
catch
{
return false;
}
}
}
}