By default Android comes with three standard fonts: Droid Sans (default font), Droid Serif, and Droid Sans Mono. They all can be applied to any view that supports styling, such as TextView, Button, by specifying the “android:typeface” attribute in the XML declaration with any of these values: sans, serif, monospace.
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sans" android:typeface="sans" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Serif" android:typeface="serif" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Monospace" android:typeface="monospace" />
Using custom fonts in Android is pretty straightforward. First find a free font and put it in the assets/fonts directory. (It’s not mandatory to have a /fonts directory, but if I have a lot of stuff in the /assets directory I organize them in separate directories). Then get a reference to your TextView and create a Typeface object specifying the font path. Lastly, apply the typeface to the TextView.
In this particular example I used the font: christmaseve.ttf
TextView textView = (TextView) findViewById(R.id.textView); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/christmaseve.ttf"); textView.setTypeface(tf);
RuntimeException: Native typeface cannot be made
If you get this exception while trying to integrate the custom font into your application, make sure the path to the font file is correct, and the font name is spelled correctly. I noticed I was getting this exception when my font path was misspelled, for example writing “.tff” instead of “.ttf”, or forgetting to add the “fonts/” prefix to the path.
Custom font used in this example provided by: http://bythebutterfly.com
Hey hey, I’d like to complete this post a little bit.
In case the font has to be changed all over the app, it is easier to override TextView’s method setTypeface and use this custom TextView in xml ( by doing instead of ), which bring us to the important part :
The createFromAsset method consumes a LOT of resources, and you basically don’t want it to be called more than once, especially during scrolling. I’d advice to create a typeface singleton that retains the typeface used so the font is not generated from the font file every time.
Ben
That actually is a good suggestion. Thank you.
Hi, I’ve just got a question. How did you do to have the code like this? I mean like this : http://img15.hostingpics.net/pics/96637658aa.png
guys don’t forget about memory leaks… it is recommended to write a singleton for handling typefaces… 😉