Xamarin.Forms 應(yīng)用程序國際化

官網(wǎng)看到關(guān)于Forms應(yīng)用程序國際化的相關(guān)內(nèi)容栓始,便一邊練習(xí)一邊總結(jié)一下屡贺,雖然這部分知識點(diǎn)很可能永遠(yuǎn)用不到=炝肌1丛堋盗誊!
原文地址:https://developer.xamarin.com/zh-cn/guides/xamarin-forms/advanced/localization/

Xamarin.Forms PCL 國際化

Forms PCL中的國際化借助資源文件(RESX)實現(xiàn)。

準(zhǔn)備資源文件

在可移植項目中添加資源文件:

添加資源文件

會在項目中生成如下兩個文件:

同時添加Resources.en.resx文件隘弊,提供英文環(huán)境下使用的字符串哈踱。記得修改文件的生成操作為EmbeddedResource

Xamarin Studio添加名稱為Resources.en資源文件時提示Resources文件已經(jīng)存在,此時可以先添加名稱為Resources1的資源文件梨熙,然后修改Resources1.resx和Resources1.Designer.resx文件的名稱為Resources.en.resx和Resources.en.Designer.resx

Designer.cs文件不做修改嚣鄙,編輯.resx文件。
Resources.resx 添加如下data元素:

<data name="home" xml:space="preserve">
        <value>首頁</value>
        <comment>home page title</comment>
</data>

Resources.en.resx 添加如下data元素:

<data name="home" xml:space="preserve">
        <value>Home</value>
        <comment>home page title</comment>
</data>

生成項目Designer.cs文件生成如下代碼:

為了獲取name為home對應(yīng)的值需要調(diào)用如下代碼
Resource.Resources.ResourceManager.GetString("home")
其中Resource為resx文件所在文件夾串结,Resources為根據(jù)文件名生成的類哑子。
簡化資源文件中字符串資源的獲取,resx文件右鍵—>屬性肌割。

修改自定義工具對應(yīng)的屬性值:ResXFileCodeGenerator修改為PublicResXFileCodeGenerator卧蜓。

ResXFileCodeGenerator,PublicResXFileCodeGenerator把敞,他們的區(qū)別是前者生成的Internal的弥奸,后者生成的是Public的資源。

重新生成項目奋早,此時可以通過如下代碼Resource.Resources.home獲取home對應(yīng)的值盛霎。

確定當(dāng)前運(yùn)行平臺的語言環(huán)境

Forms本身并沒有提供獲取運(yùn)行平臺語言環(huán)境的功能,我們需要借助dependency service 實現(xiàn)耽装。

在可移植項目中定義如下接口:

    /// <summary>
    /// Implementations of this interface MUST convert iOS and Android
    /// platform-specific locales to a value supported in .NET because
    /// ONLY valid .NET cultures can have their RESX resources loaded and used.
    /// </summary>
    /// <remarks>
    /// Lists of valid .NET cultures can be found here:
    ///   http://www.localeplanet.com/dotnet/
    ///   http://www.csharp-examples.net/culture-names/
    /// You should always test all the locales implemented in your application.
    /// </remarks>
    public interface ILocalize
    {
        /// <summary>
        /// This method must evaluate platform-specific locale settings
        /// and convert them (when necessary) to a valid .NET locale.
        /// </summary>
        CultureInfo GetCurrentCultureInfo();

        /// <summary>
        /// CurrentCulture and CurrentUICulture must be set in the platform project, 
        /// because the Thread object can't be accessed in a PCL.
        /// </summary>
        void SetLocale(CultureInfo ci);
    }

同時定義幫助類PlatformCulture

    /// <summary>
    /// Helper class for splitting locales like
    ///   iOS: ms_MY, gsw_CH
    ///   Android: in-ID
    /// into parts so we can create a .NET culture (or fallback culture)
    /// </summary>
    public class PlatformCulture
    {
        public PlatformCulture(string platformCultureString)
        {
            if (String.IsNullOrEmpty(platformCultureString))
                throw new ArgumentException("Expected culture identifier", "platformCultureString"); // in C# 6 use nameof(platformCultureString)

            PlatformString = platformCultureString.Replace("_", "-"); // .NET expects dash, not underscore
            var dashIndex = PlatformString.IndexOf("-", StringComparison.Ordinal);
            if (dashIndex > 0)
            {
                var parts = PlatformString.Split('-');
                LanguageCode = parts[0];
                LocaleCode = parts[1];
            }
            else
            {
                LanguageCode = PlatformString;
                LocaleCode = "";
            }
        }
        public string PlatformString { get; private set; }
        public string LanguageCode { get; private set; }
        public string LocaleCode { get; private set; }
        public override string ToString()
        {
            return PlatformString;
        }
    }

在App類中構(gòu)造方法中添加如下代碼愤炸,如果當(dāng)前運(yùn)行系統(tǒng)為ios或android需要獲取當(dāng)前系統(tǒng)對應(yīng).net表示的語言環(huán)境并設(shè)置為當(dāng)前的語言環(huán)境:

if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
{
    var localize = DependencyService.Get<ILocalize>();
    var ci = localize.GetCurrentCultureInfo();
    //Resource.Resources.Culture = ci;// set the RESX for resource localization
    localize.SetLocale(ci); // set the Thread for locale-aware methods
}

ios下 ILocalize 實現(xiàn)代碼

[assembly: Xamarin.Forms.Dependency(typeof(demo.iOS.Localize))]

namespace demo.iOS
{
    public class Localize : ILocalize
    {
        public void SetLocale(CultureInfo ci)
        {
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            Console.WriteLine("CurrentCulture set: " + ci.Name);
        }

        public CultureInfo GetCurrentCultureInfo()
        {
            var netLanguage = "en";
            if (NSLocale.PreferredLanguages.Length > 0)
            {
                var pref = NSLocale.PreferredLanguages[0];

                netLanguage = iOSToDotnetLanguage(pref);
            }

            // this gets called a lot - try/catch can be expensive so consider caching or something
            System.Globalization.CultureInfo ci = null;
            try
            {
                ci = new System.Globalization.CultureInfo(netLanguage);
            }
            catch (CultureNotFoundException e1)
            {
                // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
                // fallback to first characters, in this case "en"
                try
                {
                    var fallback = ToDotnetFallbackLanguage(new PlatformCulture(netLanguage));
                    Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")");
                    ci = new System.Globalization.CultureInfo(fallback);
                }
                catch (CultureNotFoundException e2)
                {
                    // iOS language not valid .NET culture, falling back to English
                    Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")");
                    ci = new System.Globalization.CultureInfo("en");
                }
            }

            return ci;
        }

        string iOSToDotnetLanguage(string iOSLanguage)
        {
            Console.WriteLine("iOS Language:" + iOSLanguage);
            var netLanguage = iOSLanguage;

            //certain languages need to be converted to CultureInfo equivalent
            switch (iOSLanguage)
            {
                case "ms-MY":   // "Malaysian (Malaysia)" not supported .NET culture
                case "ms-SG":   // "Malaysian (Singapore)" not supported .NET culture
                    netLanguage = "ms"; // closest supported
                    break;
                case "gsw-CH":  // "Schwiizertüütsch (Swiss German)" not supported .NET culture
                    netLanguage = "de-CH"; // closest supported
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }

            Console.WriteLine(".NET Language/Locale:" + netLanguage);
            return netLanguage;
        }
        string ToDotnetFallbackLanguage(PlatformCulture platCulture)
        {
            Console.WriteLine(".NET Fallback Language:" + platCulture.LanguageCode);
            var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually);

            switch (platCulture.LanguageCode)
            {
                // 
                case "pt":
                    netLanguage = "pt-PT"; // fallback to Portuguese (Portugal)
                    break;
                case "gsw":
                    netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }

            Console.WriteLine(".NET Fallback Language/Locale:" + netLanguage + " (application-specific)");
            return netLanguage;
        }
    }
}

Android下 ILocalize 實現(xiàn)代碼

[assembly: Xamarin.Forms.Dependency(typeof(demo.Droid.Localize))]

namespace demo.Droid
{
    public class Localize : ILocalize
    {
        public void SetLocale(CultureInfo ci)
        {
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            Console.WriteLine("CurrentCulture set: " + ci.Name);
        }

        public CultureInfo GetCurrentCultureInfo()
        {
            var netLanguage = "en";
            var androidLocale = Java.Util.Locale.Default;
            netLanguage = AndroidToDotnetLanguage(androidLocale.ToString().Replace("_", "-"));

            // this gets called a lot - try/catch can be expensive so consider caching or something
            System.Globalization.CultureInfo ci = null;
            try
            {
                ci = new System.Globalization.CultureInfo(netLanguage);
            }
            catch (CultureNotFoundException e1)
            {
                // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
                // fallback to first characters, in this case "en"
                try
                {
                    var fallback = ToDotnetFallbackLanguage(new PlatformCulture(netLanguage));
                    Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")");
                    ci = new System.Globalization.CultureInfo(fallback);
                }
                catch (CultureNotFoundException e2)
                {
                    // iOS language not valid .NET culture, falling back to English
                    Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")");
                    ci = new System.Globalization.CultureInfo("en");
                }
            }

            return ci;
        }

        string AndroidToDotnetLanguage(string androidLanguage)
        {
            Console.WriteLine("Android Language:" + androidLanguage);
            var netLanguage = androidLanguage;

            //certain languages need to be converted to CultureInfo equivalent
            switch (androidLanguage)
            {
                case "ms-BN":   // "Malaysian (Brunei)" not supported .NET culture
                case "ms-MY":   // "Malaysian (Malaysia)" not supported .NET culture
                case "ms-SG":   // "Malaysian (Singapore)" not supported .NET culture
                    netLanguage = "ms"; // closest supported
                    break;
                case "in-ID":  // "Indonesian (Indonesia)" has different code in  .NET 
                    netLanguage = "id-ID"; // correct code for .NET
                    break;
                case "gsw-CH":  // "Schwiizertüütsch (Swiss German)" not supported .NET culture
                    netLanguage = "de-CH"; // closest supported
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }

            Console.WriteLine(".NET Language/Locale:" + netLanguage);
            return netLanguage;
        }
        string ToDotnetFallbackLanguage(PlatformCulture platCulture)
        {
            Console.WriteLine(".NET Fallback Language:" + platCulture.LanguageCode);
            var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually);

            switch (platCulture.LanguageCode)
            {
                case "gsw":
                    netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app
                    break;
                    // add more application-specific cases here (if required)
                    // ONLY use cultures that have been tested and known to work
            }

            Console.WriteLine(".NET Fallback Language/Locale:" + netLanguage + " (application-specific)");
            return netLanguage;
        }

    }
}

代碼設(shè)置Page的Title屬性Title = Resource.Resources.home;

更改系統(tǒng)語言環(huán)境會有如下顯示效果:

英文環(huán)境
中文環(huán)境

Doesn't work in DEBUG mode (Android only)

If the translated strings are working in your RELEASE Android builds but not while debugging, right-click on the Android Project and select Options > Build > Android Build and ensure that the Fast assembly deployment is NOT ticked. This option causes problems with loading resources and should not be used if you are testing localized apps.

XAML中實現(xiàn)國際化

很多時候我們會直接在Xaml中設(shè)置文本值的顯示掉奄,如:<Label Text="Notes:" />规个。但是Xaml并沒有提供翻譯功能,需要我們通過自定義擴(kuò)展標(biāo)記(markup extension)實現(xiàn)姓建。

    [ContentProperty("Text")]
    public class TranslateExtension : IMarkupExtension
    {
        readonly CultureInfo ci;
        //指定為項目中默認(rèn)資源文件ID
        const string ResourceId = "demo.Resource.Resources";

        public TranslateExtension()
        {
            if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
            {
                ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
            }
        }

        public string Text { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {

            if (Text == null)
                return "";

            ResourceManager resmgr = new ResourceManager(ResourceId, GetType().GetTypeInfo().Assembly);

            var translation = resmgr.GetString(Text, ci);

            if (translation == null)
            {
#if DEBUG
                throw new ArgumentException(
                    String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name), "Text");
#else
                translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER
#endif
            }
            return translation;
        }
    }

Xaml中通過如下代碼設(shè)置標(biāo)題:
xmlns:local="clr-namespace:demo" Title="{local:Translate home}"

中英文顯示效果:

英文環(huán)境
中文環(huán)境

平臺元素國際化

如應(yīng)用程序的名稱诞仓、圖標(biāo)和啟動屏中涉及的元素國際化時需要在單獨(dú)的平臺項目中設(shè)置,不需要編寫代碼故不在記錄速兔。

參考:
https://developer.xamarin.com/zh-cn/guides/xamarin-forms/advanced/localization/#Localizing_Platform-Specific_Elements

http://blog.csdn.net/watermelon_/article/details/53418615

http://blog.csdn.net/chenliguan/article/details/50678678


項目地址:https://github.com/MyueX/xamarin.forms_news_demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末墅拭,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子涣狗,更是在濱河造成了極大的恐慌谍婉,老刑警劉巖舒憾,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)缕溉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進(jìn)店門待牵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人唧瘾,你說我怎么就攤上這事措译。” “怎么了饰序?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵领虹,是天一觀的道長。 經(jīng)常有香客問我求豫,道長塌衰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任蝠嘉,我火速辦了婚禮最疆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蚤告。我一直安慰自己努酸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布杜恰。 她就那樣靜靜地躺著获诈,像睡著了一般。 火紅的嫁衣襯著肌膚如雪心褐。 梳的紋絲不亂的頭發(fā)上舔涎,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機(jī)與錄音逗爹,去河邊找鬼终抽。 笑死,一個胖子當(dāng)著我的面吹牛桶至,可吹牛的內(nèi)容都是我干的昼伴。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼镣屹,長吁一口氣:“原來是場噩夢啊……” “哼圃郊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起女蜈,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤持舆,失蹤者是張志新(化名)和其女友劉穎色瘩,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體逸寓,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡居兆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了竹伸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片泥栖。...
    茶點(diǎn)故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖勋篓,靈堂內(nèi)的尸體忽然破棺而出吧享,到底是詐尸還是另有隱情,我是刑警寧澤譬嚣,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布钢颂,位于F島的核電站,受9級特大地震影響拜银,放射性物質(zhì)發(fā)生泄漏殊鞭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一尼桶、第九天 我趴在偏房一處隱蔽的房頂上張望操灿。 院中可真熱鬧,春花似錦疯汁、人聲如沸牲尺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽谤碳。三九已至,卻和暖如春溢豆,著一層夾襖步出監(jiān)牢的瞬間蜒简,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工漩仙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留搓茬,地道東北人。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓队他,卻偏偏與公主長得像卷仑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子麸折,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內(nèi)容