长话短说:我编写的应用程序支持使用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
文件选择语言的可能性。选择后,我将所选的语言保存在设置中并重新加载 MainPage
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);
}
尽管如此,只有当我关闭应用程序并再次打开它时,语言才会改变。有什么建议吗?
我解决了这个问题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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句