Thursday, March 29, 2012

Using Custom Fonts


Using Custom Fonts

Lastly we’re going to examine the process of using custom fonts. We’ll use this font for demonstration purposes. Download it and place the TTF file in the ./assets directory (create it if it doesn’t exist yet).
We’re going to use a basic layout file with a TextView, marked with an id of “custom_font” so we can access it in our code.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="vertical"  
  4.               android:layout_width="fill_parent"  
  5.               android:layout_height="fill_parent"  
  6.         >  
  7.   
  8.     <TextView  
  9.             android:id="@+id/custom_font"  
  10.             android:layout_width="fill_parent"  
  11.             android:layout_height="wrap_content"  
  12.             android:text="This is the Chantelli Antiqua font."  
  13.             />  
  14.   
  15. </LinearLayout>  
Open your main activity file and insert this into the onCreate() method:
  1. TextView txt = (TextView) findViewById(R.id.custom_font);  
  2. Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");  
  3. txt.setTypeface(font);  
The Typeface class contains a static builder method createFromAsset, which takes an AssetManager as its first parameter and a path to the file in the second argument. We’re handing it the default asset manager and the name of the font file because it’s located in the root of the “assets” folder. Once we’ve got an instance of our custom typeface, all that’s left is a call to TextView’s setTypeface() method. Simple, huh? It might also be wise to organize your fonts into a subdirectory if your assets directory is packed with other files.
There are a few potential problems that custom typefaces come with, though. Ellipsizing might not work correctly if the font doesn’t have a glyph for the special ellipsis character and internationalization might not be supported, as your font would have to handle any language that users might input. You’ll also want to keep an eye on the total size of your custom fonts, as this can grow quite large if you’re using a lot of different typefaces.
Android TextView: Using a Custom Android Font

Conclusion

This quick tip has shown you the different options that are available to you for customizing default Droid fonts. You have also learned how to include and use custom typefaces in your application. Just remember to ensure that any custom font you may be using has a license that grants you permission to use it for these purposes!

No comments: