Change Language for Xamarin Android App using Resources

落爺英雄遲暮 提交于 2021-01-29 05:15:23

问题


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?

Thanks in advance.


回答1:


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



回答2:


Have a look at the Xamarin docs: Android Localization and especially the section "GetText Method".

To retrieve translated strings in code, use the GetText method and pass the resource ID:

var cancelText = Resources.GetText (Resource.String.taskcancel);


来源:https://stackoverflow.com/questions/56901366/change-language-for-xamarin-android-app-using-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!