Currently Android does not have a native View class that supports defining a custom Typeface in your layout’s XML. After inflating your layout you can obtain a reference to the TextView and call the
setTypeface(android.graphics.Typeface) method from your Java code, but this results in unnecessary duplication of logic and violates the
The solution is to write a custom TextView implementation with support for defining custom attributes.
The first thing you should do is create the file
attrs.xml in your project’s
res/values directory. Save the following XML to your new file:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="TypefaceTextView"> <attr name="typeface" format="string" /> </declare-styleable> </resources>
This XML simply defines the custom attribute
typeface for the not yet existing class
TypefaceTextView. It also notes that the attribute value should be parsed as a string.
You can now create the new class
TypefaceTextView.java using the following source code:
You can see that the class simply looks for the custom
typeface attribute and attempts to load the named font from your application’s
assets/fonts directory at runtime. The class implements a static LruCache to avoid unnecessary hits to disk for fonts that were previously loaded. Note that if you’re targeting API levels prior to 12 the LruCache is only available using the Android support library.
Assuming you have the font file
GothamBold-Family.otf in your project’s
assets/fonts directory, then you can use the custom
TypefaceTextView class in your layouts like so:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:simple="http://schemas.android.com/apk/res/com.simple" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.simple.widget.TypefaceTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello, Gotham!" simple:typeface="GothamBold" /> </LinearLayout>
If you have another font you wish to use, simply update the value of the
simple:typeface attribute of your view. In this way you can use the same class to display a variety of custom typefaces in your Android application.