Sunday, February 17, 2013

Android beginner tutorial: Part 85 - Embedding fonts using Assets

In this tutorial we will learn how to load and use a font from an asset.

Assets are somewhat similar to resources, yet different. While resources are embedded into the application and can be referred to using the R class, assets are raw files that are stored in the assets directory and require us to manually read them to use them in our applications.

Today we'll learn how to embed and use a raw .ttf font file as an asset in our application.

First of all you need to find the ttf file. You can download fonts online, I use - all the fonts there are free and pretty good.

Once you have the .ttf file, put it in the assets directory of your project.

Then go to activity_main.xml of your application and add a TextView there:

<LinearLayout xmlns:android=""
    tools:context=".MainActivity" >
    <TextView android:layout_width="match_parent"
        android:text="Hello world!"

Now go to class and load the font using Typeface.createFromAsset() static method. Once the font is extracted, apply it to the text using setTypeface() method:

TextView mytext = (TextView)findViewById(;
Typeface face = Typeface.createFromAsset(getAssets(), "yukarimobil.ttf");

Here's the full code:

package com.example.codeforfoodtest_two;

import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity{

protected void onCreate(Bundle savedInstanceState) {

TextView mytext = (TextView)findViewById(;
Typeface face = Typeface.createFromAsset(getAssets(), "yukarimobil.ttf");

It is that easy!

You can use assets to store all sorts of files and read them byte by byte or using what's provided by the Android SDK, like the Typeface.createFromAsset() method just now.

That's all for today.

Thanks for reading!

1 comment:

Post a Comment