使用资源更改Xamarin Android App的语言 [英] Change Language for Xamarin Android App using Resources
问题描述
我需要在选择单选按钮时更改App的语言.应用已使用Android资源实现了本地化.我已经尝试过使用Activity和普通课程使用不同组合的以下解决方案,但到目前为止没有任何效果:
I have a requirement to change language of App on selection of radio buttons. App already has localization implemented using Android Resources. I have tried below solutions in different combinations from Activity as well as normal class, but nothing worked so far:
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(lang); // lang => en-US or nl-BE
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
var locale = new Java.Util.Locale(lang);
Java.Util.Locale.Default = locale;
Android.Content.Res.Configuration config = new Android.Content.Res.Configuration();
config.Locale = locale;
var context = Application.Context;
context.Resources.Configuration.Locale = locale;
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
context.Resources.UpdateConfiguration(config, context.Resources.DisplayMetrics);
string title = Application.Context.GetString(Resource.String.title_settings);
上面的标题"绝不会显示设备以外的其他语言的字符串.知道会丢失什么吗?
Above 'title' never shows string in language other than that of the device. Any idea what could be missing?
谢谢.
推荐答案
经过一番尝试之后,我找到了解决方案-发现我使用了错误的Locale构造函数,只是对其进行更改,就开始反映了更新的语言.下面是工作代码:
I found the solution after a bit of hit and trial - Found that I was using a wrong constructor of Locale, and simply changing it started reflecting the updated language. Below is the working code:
var locale = new Java.Util.Locale(lang, region); // lang => nl; region => BE
Java.Util.Locale.Default = locale;
var context = Application.Context;
context.Resources.Configuration.Locale = locale;
context.Resources.UpdateConfiguration(context.Resources.Configuration, context.Resources.DisplayMetrics);
string title = Application.Context.GetString(Resource.String.title_settings); // Reflects text in updated language
这篇关于使用资源更改Xamarin Android App的语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!