Localizing Xamarin.Forms With Hindi Language

India is a very versatile country with 23 constitutionally recognized official languages. Out of those nine can be found in the MS Global list of language codes used in providing localization to applications. What can be a better way to providean  example of localization in Xamarin forms than to provide an example to which all Indians can relate to? Our national language, Hindi, as the default documentation of Xamarin Forms provides examples in all the other languages except Hindi.

The built-in mechanism for localizing .NET applications uses RESX files and the classes in the System.Resources and System.Globalization namespaces. The RESX files containing translated strings are embedded in the Xamarin.Forms assembly, along with a compiler-generated class that provides strongly-typed access to the translations. The translation text can then be retrieved in code.
The implementation of the same in Xamarin Forms will have to be done in the platform specific code and invoke the same in portable class using Dependency Service.

Let's start coding create a new project in Xamarin/Visual Studio (see this article for steps). Add a new folder named ‘Resx’ by right clicking on the PCL project file and Selecting ‘Add’ –> ‘Add Folder’ Option. This folder will be used to save the resource files to used to implement localization, you can name it something else also but giving the name ‘Resx’ will give more clarity in understanding the purpose of the folder.
Create a new resource file inside the ‘Resx’ folder with name ‘AppResources.resx’ by right clicking on the folder then selecting Add –> New Item –> Visual C# –> Resource File. This will be the default resource file which will be used by the application in the absence of any other resource files and will contain the English language implementation for the resource keys.The file will look like following screenshot:

English Resource File

Create another resource file inside ‘Resx’ folder with name ‘AppResources.hi.resx’ by following the same above mentioned steps. This resource file will be used to store the resource keys values for Hindi language. This file will look like following Screen Shot:

Hindi Resource File

Similarly you can add resource files for other languages using the code provided in MS Global listof languages like ‘AppResources..resx’ For example Gujrati –> ‘AppResources.gu.resx’ or Sanskrit –> ‘AppResources.sa.resx’ or Punjabi — > ‘AppResources.pa.resx’ etc.

Create the interface whose methods will be implemented in platform specific codes and invoked in PCL using dependency service. The code of the interface will be like:

  1. using System.Globalization;  
  2. namespace HindiXamApp  
  3. {  
  4.     public interface ILocalize  
  5.     {  
  6.         CultureInfo GetCurrentCultureInfo();  
  7.         CultureInfo GetCurrentCultureInfo(string sLanguageCode);  
  8.         void SetLocale();  
  9.         void ChangeLocale(string sLanguageCode);  
  10.     }  
  11. }  
The First method of the interface ‘GetCurrentCultureInfo’ is for getting default culture info of the device, second one ‘GetCurrentCultureInfo(string sLanguageCode)’ is for getting culture info on the basis of provided language code, third method ‘SetLocale’ is used to set the default culture info on the basis of value got from ‘GetCurrentCultureInfo’ and ‘ChangeLocale(string sLanguageCode)’ is to change the culture info of application on the basis of provided language code.

I have named the implementation class of above interface as ‘LocaleService’ in all the platforms.The Code for iOS implementation for the interface methods will be like:

  1. using System;  
  2. using System.Globalization;  
  3. using System.Threading;  
  4.    
  5. using Foundation;  
  6. using Xamarin.Forms;  
  7.    
  8. [assembly: Dependency(typeof(HindiXamApp.iOS.LocaleService))]  
  9. namespace HindiXamApp.iOS  
  10. {  
  11.     public class LocaleService : ILocalize  
  12.     {  
  13.         public CultureInfo GetCurrentCultureInfo()  
  14.         {  
  15.             var iosLocaleAuto = NSLocale.AutoUpdatingCurrentLocale.LocaleIdentifier;    // en_FR  
  16.             var iosLanguageAuto = NSLocale.AutoUpdatingCurrentLocale.LanguageCode;      // en  
  17.             var netLocale = iosLocaleAuto.Replace("_""-");  
  18.             const string defaultCulture = "en";  
  19.    
  20.             CultureInfo ci = null;  
  21.             if (NSLocale.PreferredLanguages.Length > 0)  
  22.             {                 
  23.                 try  
  24.                 {  
  25.                     var pref = NSLocale.PreferredLanguages[0];  
  26.                     var netLanguage = pref.Replace("_""-");  
  27.                     ci = CultureInfo.CreateSpecificCulture(netLanguage);  
  28.                 }  
  29.                 catch  
  30.                 {  
  31.                     ci = new CultureInfo(defaultCulture);  
  32.                 }  
  33.             }  
  34.             else  
  35.             {  
  36.                 ci = new CultureInfo(defaultCulture); // default, shouldn't really happen <img draggable="false" class="emoji" alt="" src="https://s.w.org/images/core/emoji/72x72/1f642.png">  
  37.             }  
  38.             return ci;  
  39.         }  
  40.         public CultureInfo GetCurrentCultureInfo(string sLanguageCode)  
  41.         {  
  42.             return CultureInfo.CreateSpecificCulture(sLanguageCode);  
  43.         }  
  44.         public void SetLocale()  
  45.         {  
  46.             var ci = GetCurrentCultureInfo();  
  47.             Thread.CurrentThread.CurrentCulture = ci;  
  48.             Thread.CurrentThread.CurrentUICulture = ci;  
  49.             Console.WriteLine("SetLocale: " + ci.Name);  
  50.         }  
  51.         public void ChangeLocale(string sLanguageCode) {  
  52.             var ci = CultureInfo.CreateSpecificCulture(sLanguageCode);  
  53.             Thread.CurrentThread.CurrentCulture = ci;  
  54.             Thread.CurrentThread.CurrentUICulture = ci;  
  55.             Console.WriteLine("ChangeToLanguage: " + ci.Name);  
  56.         }        
  57.     }  
  58. }  
The Code for Android implementation will be like:
  1. using System;  
  2. using System.Globalization;  
  3. using System.Threading;  
  4. using Xamarin.Forms;  
  5.    
  6. [assembly: Dependency(typeof(HindiXamApp.Droid.LocaleService))]  
  7. namespace HindiXamApp.Droid  
  8. {  
  9.     public class LocaleService : ILocalize  
  10.     {  
  11.         public CultureInfo GetCurrentCultureInfo()  
  12.         {  
  13.             var androidLocale = Java.Util.Locale.Default; // user's preferred locale  
  14.             var netLocale = androidLocale.ToString().Replace("_""-");  
  15.   
  16.             #region Debugging output  
  17.             Console.WriteLine("android:  " + androidLocale.ToString());  
  18.             Console.WriteLine("netlang:  " + netLocale);  
  19.    
  20.             var ci = new CultureInfo(netLocale);  
  21.             Thread.CurrentThread.CurrentCulture = ci;  
  22.             Thread.CurrentThread.CurrentUICulture = ci;  
  23.             Console.WriteLine("thread:  " + Thread.CurrentThread.CurrentCulture);  
  24.             Console.WriteLine("threadui:" + Thread.CurrentThread.CurrentUICulture);  
  25.             #endregion  
  26.    
  27.             return ci;  
  28.         }  
  29.         public CultureInfo GetCurrentCultureInfo(string sLanguageCode)  
  30.         {  
  31.             return CultureInfo.CreateSpecificCulture(sLanguageCode);  
  32.         }  
  33.         public void SetLocale()  
  34.         {  
  35.             var ci = GetCurrentCultureInfo();  
  36.             Thread.CurrentThread.CurrentCulture = ci;  
  37.             Thread.CurrentThread.CurrentUICulture = ci;  
  38.         }  
  39.         public void ChangeLocale(string sLanguageCode)  
  40.         {  
  41.             var ci = CultureInfo.CreateSpecificCulture(sLanguageCode);  
  42.             Thread.CurrentThread.CurrentCulture = ci;  
  43.             Thread.CurrentThread.CurrentUICulture = ci;  
  44.             Console.WriteLine("ChangeToLanguage: " + ci.Name);  
  45.         }  
  46.     }  
  47. }  
Since we are also going to use the values of resource files in XAML, we will have to write XAML extensions to read the values from from resource files. So create a new class by the name of ‘TranslateExtension’ and copy following code inside it.
  1. using System;  
  2. using System.Globalization;  
  3. using System.Reflection;  
  4. using System.Resources;  
  5. using Xamarin.Forms;  
  6. using Xamarin.Forms.Xaml;  
  7.    
  8. namespace HindiXamApp  
  9. {  
  10.     [ContentProperty("Text")]  
  11.     public class TranslateExtension : IMarkupExtension  
  12.     {  
  13.         readonly CultureInfo ci;  
  14.         const string ResourceId = "HindiXamApp.Resx.AppResources";  
  15.    
  16.         public TranslateExtension()  
  17.         {  
  18.             if (string.IsNullOrEmpty(App.CultureCode))  
  19.             {  
  20.                 ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();  
  21.             }  
  22.             else ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo(App.CultureCode);  
  23.         }  
  24.    
  25.         public string Text { getset; }  
  26.    
  27.         public object ProvideValue(IServiceProvider serviceProvider)  
  28.         {  
  29.             if (Text == null)  
  30.                 return "";  
  31.    
  32.             ResourceManager temp = new ResourceManager(ResourceId , typeof(TranslateExtension).GetTypeInfo().Assembly);  
  33.             var translation = temp.GetString(Text, ci);  
  34.             if (translation == null)  
  35.             {  
  36. #if DEBUG  
  37.                 throw new ArgumentException(string.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name), "Text");  
  38. #else  
  39.                 translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER  
  40. #endif  
  41.             }  
  42.             return translation;  
  43.         }  
  44.     }  
  45. }  
This completes the translation related code changes of the application, now let's create the UI of the application. The application will have a Xamarin Forms ContentPage which will have picker containing list of languages and table containing some static values.The static values of the table will by default appear in English and when the user selects ‘हिन्दी’ from the picker the content will change to Hindi. I want to give user the freedom to choose the language in app rather than changing the language from device settings that's the reason I added ‘GetCurrentCultureInfo(string sLanguageCode)’ and‘ChangeLocale(string sLanguageCode)’ in the code. The XAML code of the ‘HomePage’ is as follows:
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:lEx="clr-namespace:HindiXamApp;assembly=HindiXamApp"  
  5.              x:Class="HindiXamApp.HomePage">  
  6.   <ContentPage.Padding>  
  7.     <OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0" />  
  8.   </ContentPage.Padding>  
  9.   <ContentPage.Content>  
  10.     <Grid>  
  11.       <Grid.RowDefinitions>  
  12.         <RowDefinition Height="*"/>  
  13.         <RowDefinition Height="*"/>  
  14.         <RowDefinition Height="*"/>  
  15.         <RowDefinition Height="*"/>  
  16.         <RowDefinition Height="*"/>  
  17.         <RowDefinition Height="*"/>  
  18.         <RowDefinition Height="*"/>  
  19.         <RowDefinition Height="*"/>  
  20.       </Grid.RowDefinitions>  
  21.       <Grid.ColumnDefinitions>  
  22.         <ColumnDefinition Width="10"/>  
  23.         <ColumnDefinition Width="*"/>  
  24.         <ColumnDefinition Width="*"/>  
  25.         <ColumnDefinition Width="10"/>  
  26.       </Grid.ColumnDefinitions>  
  27.       <Label Grid.Row ="0" Grid.Column="1" Text="{lEx:Translate SelectLanguage}" />  
  28.       <Picker  Grid.Row="0" Grid.Column="2" x:Name="pkrLanguage" SelectedIndexChanged="OnPickerChanged" WidthRequest="50" >  
  29.         <Picker.Items>  
  30.           <x:String>English</x:String>  
  31.           <x:String>हिन्दी</x:String>  
  32.         </Picker.Items>  
  33.       </Picker>  
  34.       <Label Grid.Row ="1" Grid.Column="1" Text="{lEx:Translate Name}" />  
  35.       <Label Grid.Row="1" Grid.Column="2"  Text ="{lEx:Translate NameValue}" />  
  36.       <Label Grid.Row ="2" Grid.Column="1" Text="{lEx:Translate DateOfBirth}" />  
  37.       <Label Grid.Row="2" Grid.Column="2" Text ="{lEx:Translate DOBValue}"/>  
  38.       <Label Grid.Row ="3" Grid.Column="1" Text="{lEx:Translate Gender}" />  
  39.       <Label Grid.Row="3" Grid.Column="2" Text ="{lEx:Translate GenderValue}"/>  
  40.       <Label Grid.Row ="4" Grid.Column="1" Text="{lEx:Translate Address}"  />  
  41.       <Label Grid.Row="4" Grid.Column="2" Text ="{lEx:Translate AddressValue}" />  
  42.       <Label Grid.Row ="5" Grid.Column="1" Text="{lEx:Translate State}"  />  
  43.       <Label Grid.Row="5" Grid.Column="2" Text ="{lEx:Translate StateValue}" />  
  44.       <Label Grid.Row ="6" Grid.Column="1" Text="{lEx:Translate Country}"/>  
  45.       <Label Grid.Row="6" Grid.Column="2" Text ="{lEx:Translate CountryValue}" />  
  46.     </Grid>     
  47.   </ContentPage.Content>  
  48. </ContentPage>  
As it can be seen fron the above code that we are using ‘{lEx:Translate HomeButtonXaml}’ to set the text of the variables on basis of resource file values and lEx: is declared as local namespace xmlns:lEx=”clr-namespace:HindiXamApp;assembly=HindiXamApp” this basically let us use the above declared TranslateXAML extension.

The code written in code behind of ‘HomePage’, which contains the implementation of language change is as follows:

  1. using System;  
  2. using Xamarin.Forms;  
  3.    
  4. namespace HindiXamApp  
  5. {  
  6.     public partial class HomePage : ContentPage  
  7.     {  
  8.         public HomePage()  
  9.         {  
  10.             InitializeComponent();  
  11.         }  
  12.    
  13.         public void OnPickerChanged(object sender, EventArgs args)  
  14.         {  
  15.             var vSelectedValue = pkrLanguage.Items[pkrLanguage.SelectedIndex];  
  16.             if (vSelectedValue.Trim() == "हिन्दी")  
  17.             {  
  18.                 DependencyService.Get<ILocalize>().ChangeLocale("hi");  
  19.                 App.CultureCode = "hi";  
  20.             }  
  21.             else  
  22.             {  
  23.               DependencyService.Get<ILocalize>().SetLocale();  
  24.               App.CultureCode = string.Empty;  
  25.             }  
  26.             var vUpdatedPage = new HomePage();  
  27.             Navigation.InsertPageBefore(vUpdatedPage, this);  
  28.             Navigation.PopAsync();  
  29.         }  
  30.     }  
  31. }  
As it can be seen from the above code, we are changing the culture of the application in‘OnPickerChanged’ event using dependency service code ‘ DependencyService.Get().ChangeLocale(“hi”);’, after that we are setting the value of application level static variable ‘App.CultureCode’ so that translate extension should be able to get the respective culture info from platform and lastly we are creating a new object of home page and adding it to Navigation stack as updated culture info won’t work on the existing page object because it’s resources are already loaded. I have implemented an if statement as I am showing the example for only 2 languages if you are giving options for more languages I suggest to use switch statement.

This is how the application will look on execution:

iOS Simulator:

iOS Example

Video Player


Android Simulator:

Video Player

I have just implemented the one aspect of implementing localization .i.e. user Interface localization, but in order to make the application completely localized the database of the application should also support that which will change depending upon the need/requirements of the application. This application right now only supports Hindi, however I would request everyone who knows/understand the other nine Indian languages to fork the code on Github, add the resource file of those languages so that we could share the example containing all the Indian languages :).You can use this translator which I used to write Hindi. Let me know if I have missed anything or you have any queries/suggestions.

Reference : Official Xamarin Forms Documentation

Read more articles on Xamarin:

Up Next
    Ebook Download
    View all
    Learn
    View all