Android TextView with custom Typeface support

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( method from your Java code, but this results in unnecessary duplication of logic and violates the DRY principle.

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"?>
    <declare-styleable name="TypefaceTextView">
        <attr name="typeface" format="string" />

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 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=""
    android:orientation="vertical" >
        android:text="Hello, Gotham!"
        simple:typeface="GothamBold" />

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.

4 thoughts on “Android TextView with custom Typeface support

  1. It’s not wroking for me (Android API 8). First when i type “xmlns:simple=”” (I have named my package the same as you) I’m getting an error: “No resource identifier found for attribute “typeface” in package com.simple”. So I rename it to “xmlns:simple=””
    And now it’s okay but when i run it on my device i’m getting only errors:
    12-17 14:02:54.349: E/AndroidRuntime(9681): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.artest.tvplus/com.artest.tvplus.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class com.artest.tvplus.TypefaceTextView

    Can you help me ? Thanks in advance

  2. Pingback: Building a Greek Lexicon and Grammar for Android » Ben Linskey

Comments are closed.