[MonoTouch] Multi-lingual

Göran Halvarsson goranhalvarsson at gmail.com
Fri Oct 7 09:35:06 EDT 2011


Hello

I made something similar, but in stead of using DB I used good old
localizable folders:
sv.proj
--Localizable.strings
en.proj
--Localizable.strings

In the "swedish" Localizable.strings:
"Offers" = "Erbjudande";
"Barcode" = "Streckkod"

Display a label:
Locale.GetText ("Offers");

Switch Language, let say you have a settings view where you select a language:
Locale.ChangeCulture(MyApp.Instance.CurrentUser.Culture);

Don't forget to reload your view after the "switch". I did a flip
animation to spice it up...
Task.Factory.StartNew( () => ReloadView() );


private void ReloadView()
{
	InvokeOnMainThread(delegate {
					
		//Flip the view
		UIView.BeginAnimations("Flipper");
		UIView.SetAnimationDuration(1.25);
		UIView.SetAnimationCurve(UIViewAnimationCurve.EaseInOut);
		UIView.SetAnimationTransition
(UIViewAnimationTransition.FlipFromRight, _tabbarController.View ,
true);
		_tabbarController.ViewWillDisappear(true);
		_tabbarController.ViewWillAppear(true);
		UIView.CommitAnimations();
			
	});
}


The class:
public static class Locale
{
		
	public static CultureInfo DefaultCultureInfo = new CultureInfo("sv-SE");
	private static CultureInfo _currentCultureInfo = DefaultCultureInfo;
		
		
	public static void ChangeCulture(string cultureInfo)
	{
		_currentCultureInfo = new CultureInfo(cultureInfo);
	}
		
	public static CultureInfo GetPhoneCultureInfo()
	{
		return new CultureInfo(NSLocale.CurrentLocale.LocaleIdentifier.Replace("_","-"));
	}
		
		
	public static string GetText (string str)
	{
		string path = null;
		path = NSBundle.MainBundle.PathForResource(_currentCultureInfo.TwoLetterISOLanguageName.ToLower(),"lproj");
		NSBundle languageBundle = NSBundle.FromPath(path);
			
		return languageBundle.LocalizedString(str,string.Empty);
			
	}
		

		
	public static string Format (string fmt, params object [] args)
	{
		fmt = NSBundle.MainBundle.LocalizedString(fmt,"");
		return String.Format (fmt, args);
	}


    public static CultureInfo GetCultureInfo(string countryCode)
    {
        CultureInfo currentCulture = null;

        foreach (CultureInfo ci in
CultureInfo.GetCultures(CultureTypes.AllCultures))
        {

            if (ci.Name.ToLower().Contains(countryCode.ToLower()))
            {

                currentCulture = ci;
                break;
            }



        }

        return currentCulture;

    }
}
		
That's it really...
(I must say that I just love the System.Threading.Task.Factory:
http://www.codethinked.com/net-40-and-systemthreadingtasks)

I hope it will help you.

Br
Göran


More information about the MonoTouch mailing list