[Android] Setting the Font in a View

Sometime ago, I was asked how to control the font used in a customised view. In the customised view, the onDraw method is overridden and had code looking like this:

Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
canvas.drawText("Text to display", posX,
    posY, textPaint);

To change the font, Paint has a setTypeface method. This method takes in a Typeface object, which determines which font is used. The Typeface class has a number of static methods to create the instance for us. If you want to use TrueType Font file, place the file in assets folder, like how this:

TTF file in the assets

Now in the code, we can use the createFromAsset method to create the Typeface object and set the Paint to use it. With the additional lines, the code fragment now looks like this (the added lines are in bold):

Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
Typeface font = Typeface.createFromAsset(
    getContext().getAssets(), 
    "fonts/androidnation.ttf");
textPaint.setTypeface(font);
canvas.drawText("Text to display", posX, posY,
    textPaint);

Typeface also has a few fonts that are already defined and can be loaded without having to additional font files. These fonts are defined as public constants in Typeface and they are listed in the documentation for Typeface. For example, to set the Paint to use the default bold font:

textPaint.setTypeface(Typeface.DEFAULT_BOLD);

The other fonts defined accessible as constants from Typeface are serif, sans serif and monospace.

The font of text inside a TextView can also be changed using its setTypeface method. Like the one for Paint, it also takes in a Typeface as an argument. If the TextView is being specified in a layout XML file, the font can be changed using the android:typeface attribute. For example.

<TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Customised Font"
    android:typeface="monospace" />

However, the fonts must be either normal, sans, serif or monospace.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: