我正在尝试创建一个支持多标签语言的应用程序,其中我有一个设置页面,允许用户选择一种语言,然后视图模型将使用MessagingCenter发布一条消息,最后,MainActivity将响应此消息
这就是上面提到的代码示例
private async void HandleSelectedLanguageChanged()
{
if (SelectedLanguage == null || !this.isInitialized)
return;
MessagingCenter.Send(this, Constants.LanguageChanged, SelectedLanguage);
ShowLoading();
await Task.Delay(1000);
await NavigationService.NavigateAsync($"/{Routes.Landing}/{CallbackPage ?? Routes.Login}");
HideLoading();
}MainAcitivty
CultureInfo.CurrentCulture = selectedCulture;
CultureInfo.CurrentUICulture = selectedCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = selectedCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = selectedCulture;
var selectedCulture = Common.Settings.Settings.CurrentCultureInfo.ToDescriptionString().Split('-');
if (selectedCulture.Length == 2)
{
var selectedLang = selectedCulture[0];
var selectedCountry = selectedCulture[1];
var locale = new Java.Util.Locale(selectedLang, selectedCountry);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration { Locale = locale };
Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
}为了这个问题,MainActivity中的代码被简化了,有些特定于设备的文化配置与这个问题无关,我还确保selectedCulture包含预期的区域性,创建这个对象的代码与这个问题无关。
奇怪的是,文化只对我导航到的第一页进行了更改,并返回到应用程序中的其他页面。下面是我所使用的翻译MarkupExtension的代码
ContentProperty("Text")公共类BaseTranslateExtension : IMarkupExtension {私有字符串_resourceId;
public BaseTranslateExtension(string resourceId, Type assemblyType)
{
_resourceId= resourceId;
_assemblyType = assemblyType;
}
public string Text { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Text == null)
return null;
ResourceManager resourceManager = new ResourceManager(_resourceId, _assemblyType.GetTypeInfo().Assembly);
return resourceManager.GetString(Text, CultureInfo.CurrentCulture);
}
}CurrentCulture似乎只为第一页设置为新的区域性,对于每一个其他页面,它只是相同的旧值,这很奇怪,因为它是一个静态属性,我确信它在代码的其他地方没有被设置
发布于 2020-07-23 09:49:33
我在Android资源中没有语言字符串,但在(旧的?)重新整理文件。也许这就是为什么我可以使用以下解决方案:还可以设置默认线程的区域性。
string cultureCode = GetUserRequestedAppCultureCode(); // For example: "en-US".
var selectedCulture = new CultureInfo(cultureCode);
CultureInfo.DefaultThreadCurrentCulture = selectedCulture;
CultureInfo.DefaultThreadCurrentUICulture = selectedCulture;
CultureInfo.CurrentCulture = selectedCulture;
CultureInfo.CurrentUICulture = selectedCulture;对于Xamarin.Android,只在(每个)应用程序启动时运行这段代码就足够了。您也可以在运行时以这种方式切换语言,而无需重新启动应用程序。
https://stackoverflow.com/questions/59714764
复制相似问题