Using custom fonts in Android is quite simple, but requires to do some things programmatically and cannot be done using only XML file defining the view. Let’s have a look on an example.
Here we have a simple Android view file:
hint: if you cannot see the code below, please disable AdBlock on this site (I don’t have advertisements, but I’m using Gist)
We want to use custom font for the TextView element with id: custom_font. Firstly, we have to put our font (in this example: Custom_Font.ttf) into the ./assets directory (create it if it doesn’t exist yet) in the main directory of the project. Then, we can use the following code:
Please note, that Android does not fully support fonts in *.otf format, so it’s safer to use *.ttf format instead.
If we have font only in *.otf format, we can use one of the free font converters in order to obtain desired and proper file extension.
When we use the same font in whole application or a lot of elements in our project should use it, we can create custom TextView.
The only thing, we have to do, is to create an additional class extending default TextView class.
Note: isInEditMode() method is used for graphical preview of the UI in Eclipse IDE.
Afterwards, inside the view in the XML file, we should replace default TextView with our custom TextView like in the example below.
You can create other custom widgets respectively. E.g. MyButton, MyCheckBox, etc.
It can be useful, when you want to unify fonts in your application taking into consideration older versions of the Android.
Please note, that Roboto font was introduced in Android Ice Cream Sandwich, but luckily is free and available for download from official Google website.
Further reading & references:
Update: There is a library, which simplifies described process. Check it out here: https://github.com/ikocijan/MagicViews.