在Xamarin Forms中改变语言

问题描述 投票:0回答:1

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

我直接在xaml中应用字符串,使用

`xmlns:resources="clr-namespace:Elettric80.TP.Translations"`

ContentPage 初始声明,以及

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

在需要的地方。

在代码方面,我只需将翻译好的字符串用 LangResource.{string}.

在MainPage的子页面Option中,我提供了基于可用的语言选择的可能性。resx 一旦选定,我就会在设置中保存选定的语言,然后用

Application.Current.MainPage = new MainPage();

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

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);
}

但是,只有当我关闭应用程序并再次打开它时,语言才会发生变化,有什么建议吗?

c# xamarin.forms xamarin.android translation
1个回答
0
投票

我用以下方法解决了这个问题 DependencyService呼叫

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

传递所选择的语言(格式为 "en""es""it "等)。

该接口在ILanguageService.cs中声明为。

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

安卓方面的情况如下。

[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);
© www.soinside.com 2019 - 2024. All rights reserved.