簡體   English   中英

無法在運行時更改應用程序語言 Xamarin Forms -> Android

[英]Unable to change app language at runtime on Xamarin Forms -> Android

我正在使用 Xamarin Forms 開發跨平台應用程序,主要目標 Android。 我正在開發的應用程序是指語言的.resx文件。 由於手機設置為不同的語言,因此翻譯工作正常。

如何在運行時從應用程序設置中即時切換語言?

我嘗試使用DependencyService在 Android 端調用 function ,但是,盡管返回沒有錯誤,但它並沒有改變語言。

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;
            }
        }
    }
}

看看CurrentCultureCurrentUiCulture

據我記得,您可以在運行時設置它們。

我猜你正在使用帶有MarkupExtensioni18n 如果是這樣,那么您可以動態更改Translate擴展類的 ctor 中的文化。

namespace ResxLocalize
{
    [ContentProperty("Text")]
    public class TranslateExtension : IMarkupExtension
    {
        private readonly CultureInfo ci;
        private const string ResourceId = "MyApp.Resources.R";

        public TranslateExtension()
        {
            if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
            {
                // SET YOUR CULTURE HERE
                ci = new CultureInfo("DESIRED CULTURE");
            }
        }

        public string Text { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            string translation = string.Empty;

            if (Text != null)
            {
                ResourceManager manager = new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly);

                translation = manager.GetString(Text, ci) ?? Text;
            }

            return translation;
        }
    }
}

每次獲取字符串時,都會觸發一個新的 ctor 並動態檢索文化。 您可以在此處更改 ctor 內的 CultureInfo: ci = new CultureInfo("DESIRED CULTURE");

您可以在此處查看使用 App 屬性的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM