James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code



Beautiful Android Compat Roboto Fonts in Xamarin.Android

In android 4.1 and 4.2 Google did something amazing, which was add the roboto fonts as a default font family that you can switch between. It is as easy as setting “sans-serif”, “sans-serif-light”, “sans-serif-condensed”, and “sans-serif-thin” as the android:FontFamily.

However the obvious issue here is that this is only available in 4.1+ (with thin only being available in 4.2). So if you want to target older platforms you have to do some custom themes, or different layouts and that is no fun for anyone. These fonts are beautiful and everyone should be able to use them. It is also completely possible since you are able to load custom fonts. In Xamarin.Android it is extremely simple. All you have to do is add your fonts to you asset folder and then:

Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-LightItalic.ttf");

However this is going to be no fun if you have to set it in the code behind for each and every text view. We want to set it in the axml! To do this we are going to have a custom TextView (we will call it RobotoTextView) and it will have a custom attribute (we will call it typeface).

The RobotoTextView will check the custom attribute for the typeface attribute (such as roboto_thin or roboto_light) and then load up the correct font to display. It will also do some caching as well so we don’t load them up tons of times.

After that it is as simple as putting some stuff in you axml. First is to add an xmlns definition. I like to use res-auto and let it figure it out:


Then just a com.refractored.controls.RobotoTextView instead of TextView and set this property:


Now you are all set! I have setup a full github repo with source code and example!

Your result will look like this:

Copyright © James Montemagno 2013 All rights reserved. Privacy Policy

View Comments