2016年8月11日 星期四

How to use custom font

1.How to use custom font
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.
Download it and place the TTF file in the ./assets directory (create it if it doesn't exist yet).


Open your main activity file and insert this into the onCreate() method:
1
2
3
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");
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.