在 Xamarin Forms 中更改语言

Changing language in Xamarin Forms

长话短说: 我编写的应用程序支持多种语言,使用 Translation 文件夹中的 LangResource.{xx-XX}.resx 个文件。

我使用

直接在 xaml 中应用字符串
`xmlns:resources="clr-namespace:Elettric80.TP.Translations"`

ContentPage初始声明中,并且

`Text="{x:Static resources:LangResource.{string}}"` 

需要的地方。

在代码方面,我只是使用 LangResource.{string} 分配翻译后的字符串。

在 MainPage 的子页面 Option 中,我提供了 select 一种基于可用 resx 文件的语言的可能性。 selected 后,我将 selected 语言保存在设置中,并使用

重新加载 MainPage
Application.Current.MainPage = new MainPage();

当应用程序重新启动时,我读取设置,获取 selected 语言并执行

Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);

在调用 InitializeComponent(); 之前。

问题是MainPage翻译好了,但是其他页面都保持原来的语言,除非我关闭应用程序,然后手动重启。

我也试过使用DependencyService直接在Android端应用语言:

DependencyService.Get<ILanguageService>().SetLanguage(lang);

在 c# 中并将语言传递给以下方法

public void SetLanguage(string lang)
{
    CultureInfo myCulture = new CultureInfo(lang);
    CultureInfo.DefaultThreadCurrentCulture = myCulture;

    Locale locale = new Locale(lang);
    Locale.Default = locale;
    var config = new global::Android.Content.Res.Configuration();
    config.Locale = locale;
    config.SetLocale(locale);
}

不过,只有当我关闭应用程序并再次打开时,语言才会改变。 有什么建议吗?

我用 DependencyService 解决了这个问题,调用

DependencyService.Get<ILanguageService>().SetLanguage(lang);

传递已选择的语言(格式为 "en"/"es"/"it"/etc...)。

接口在ILanguageService.cs中声明为:

namespace {namespace}
{
    public interface ILanguageService
    {
        void SetLanguage(string lang);
    }
}

Android方如下:

[assembly: Dependency(typeof({namespace}.Droid.LanguageService))]

namespace {namespace}.Droid
{
    public class LanguageService : ILanguageService
    {
        public void SetLanguage(string lang)
        {
            if (!string.IsNullOrEmpty(lang))
            {
                // Get application context
                Context context = Android.App.Application.Context;

                // Set application locale by selected language
                Locale.Default = new Locale(lang);
                context.Resources.Configuration.Locale = Locale.Default;
                context.ApplicationContext.CreateConfigurationContext(context.Resources.Configuration);
                context.Resources.DisplayMetrics.SetTo(context.Resources.DisplayMetrics);

                // Relaunch MainActivity
                Intent intent = new Intent(context, new MainActivity().Class);
                intent.AddFlags(ActivityFlags.NewTask);
                context.StartActivity(intent);
            }
        }
    }
}

和之前一样,我将应用程序设置为所选语言,从设置中读取它并使用

应用它
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);