我正在使用Xamarin Forms(主要目标Android)开发跨平台应用程序。我正在使用的应用指的是.resx
语言文件。手机设置为其他语言后,翻译效果很好。
如何在运行时即时从应用程序设置中切换语言?
我尝试使用DependencyService
来在Android端调用函数,但是尽管没有错误返回,但它不会更改语言。
C#项目
bool test = DependencyService.Get<ILanguageService>().SetLanguage(selectedLang.StringValue);
Android专案
[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;
}
}
}
}
看一下CurrentCulture和CurrentUiCulture。
据我记得,您可以在运行时设置它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句