Android Custom Fonts | AndroidMonks

Android Custom Fonts – Add your Own Font

In this tutorial, we will go over and above and see how to add Android Custom Fonts to the UI of the Android Application. In order to know what custom fonts are, you will have to understand the difference between various specifics related to fonts.

We will go over each and every term used to represent a Font and see how to create/add a Font to your project.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

There have been techniques that have evolved over the period. From Android 8.0, there is an option to add Font as a resource file just like you add String and Drawables.

In the older versions, you will have to load the Font Asset, create a Typeface object and use it throughout your Application.

We will be going over both the techniques in the below tutorial. But before all that, let us take a moment to understand what the different terms mean and what they do to your Font.

Understanding TypeFaces

Before we jump on to creating Assets, Fonts etc, we will have to understand the very basic of a representation of a Letter in our Digital medium. The letter representation has a lot of parts to it, changing these parts creates our Fonts.

In Android, you have the option to change the TypeFace of a String, this means that you have the option to change the very face of a Font. See the example below,

Typeface difference
Typeface difference

As you can see above, there are 2 different representation of the same letter. The major difference lies in the way, the letters are projected to the user.

The first letter is of the typeface called sans and the letter to the right is of the TypeFace serif.

The word TypeFace is used to mean the way or style of representing a Letter in the old times. There were not different calligraphies back then and the only way of printing a letter was through metal blocks. So in order to distinguish a style from one another the concept of TypeFaces came about. The Fonts are derived from the TypeFaces (Like mentioned above, these are parts that can be moved around to create a Font).

In Android, you can create four major TypeFaces, namely Serif, Sans, normal and monospace.

Left is normal, Right is a monospace
Left is normal, Right is a monospace

Each of the TypeFace gives a distinguishing characteristic to the Alphabet. These TypeFaces act as the first layer of creating a Font. We will be moving on to know more about what a FontFamily is, what textStyle in Android means and the difference between a TypeFace and Font in detail below.

TextStyle in Android

The next most looked upon topic is the use of TextStyle in Android. This takes in values: bolditalic and normal either individually or combined. What they mean is that you can alter a span of the Text by creating a different dynamics to the Alphabet.

See the example below to what the TextStyle does to an Android Text.

Left: Bold Right: Italic
Left: Bold Right: Italic

 

FontFamily in Android

A font family is a grouping of Fonts that have the same design. A good example will be Times New Roman, which contains an Italic TextStyle to it, Serif TypeFace and Bold TextStyle also.

This type of Grouping the TextStyle and TypeFace creates a mixture of Fonts that are interpreted by the end user to be a Font in itself.

You can create a Font Family in Android using the android:fontFamily attribute. This way, you can combine fonts to give the Alphabet a different style.

A sample Font Family with the value set looks like this,

serif-monospace
serif-monospace

I have combined the serif and monospace to create the Font looking like the above letter. You can try out various combinations, including sans-serif-condensed, serif-condensed, serif-smallcaps etc.

Creating Custom Fonts in Android 101 (For API < 28)

You now have a better understanding of what the different parts of a Fonts are, and the capability to which the Android leverages the preset fonts that are available.

In this section, we will look at code examples to including a custom font into your project. This is a bit tedious since the current Android versions allow the developer to include the fonts as a resource directly like a string or a drawable.

We will see about it in the next section. But this section is devoted to implementing custom fonts in the lower API levels.

Creating Custom Fonts in Android 101 (For API < 28)

You now have a better understanding of what the different parts of a Fonts are, and the capability to which the Android leverages the preset fonts that are available.

In this section, we will look at code examples to including a custom font into your project. This is a bit tedious since the current Android versions allow the developer to include the fonts as a resource directly like a string or a drawable.

We will see about it in the next section. But this section is devoted to implementing custom fonts in the lower API levels.

The current version of Android leverages including the Fonts into your project just like any other resource, See the steps below

Project Structure : Font resource
Project Structure: assets>fonts

Like you can see above, there is a assets directory created. The directory contains the fonts folder inside it.

 

This structure is essential in order to help the compiler understand about the .ttf files that need to be present.

Load the resource

Once the Font Folder is created, time to place our Fonts in form of a .ttf file. I have placed 4 font files in the form of .otf/.ttf extensions. 

I find the font resources from sites like dafont, 1001freefonts. These sites are resourceful enough and filled with a lot of different fonts for the need. Download the TTF file and place it inside the fonts folder as I have done above.

Create a CustomFonts Wrapper Class

The next step along the line will be to create a Wrapper Class for TextViews to be able to use our Font. We will be leveraging the TypeFace class and set it to the TextView object we have created.

This type of creating Custom Fonts limits the developer to one View at a time only, in case there is a need for Custom Fonts for a Button. we will have to re-implement the same for a Button Class and create a wrapper for it.

This is definitely a tedious process, but still, there isn’t any workaround at the moment.

To create our Wrapper, we will override the TextView class like below. The below representation is inside a directory named java>customFonts>MyTextView_Bold.java

CustomFonts inside java
customfonts inside java

MyTexyView_Bold.java

package customfonts;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;


public class MyTextView_Medium extends TextView {

    public MyTextView_Medium(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyTextView_Medium(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView_Medium(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-Regular.ttf");
            setTypeface(tf);
        }
    }
}

Like you can see above, we have overridden the constructor with 3 different signatures. These are important so that, we can leverage our Custom Font from anywhere. Meaning, a Layout implementation is possible and at the same time Activity implementation is also possible.

The TypeFace class contains the createFromAsset method, that can point to the .otf file we have stored inside the fonts folder. This implementation is important in order to be able to set the TypeFace to our TextView.

Follow the same steps in case there is a need to create custom fonts for a Button. You will have to override the Button Class and implement the init() method like above.

Include it in Layout

Once the Custom Fonts class is created it is time to include it inside the Layout file. The XML inclusion is pretty straightforward. You can straight away call the custom fonts as your Root Layout. See the below implementation.

<customfonts.MyTextView_Bold
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/title"
    android:textSize="100sp"/>

The customfonts is the folder inside which our custom fonts class is. This dot separated way of calling is straightforward enough. You can call any number of classes this way.

Include it in your Activity

Time to see how the Activity implementation of the Custom Font is.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class CustomFontsImple extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        customfonts.MyTextView_Bold textViewBold = findViewById(R.id.textStart);
    }
}

Since we use the public class inside our customfonts folder, we can directly call the class. Once done, we will be able to assign to an object of a Class and make use of it in the lifetime of the activity.

Creating Custom Fonts for API > 28

Much simpler incorporation of fonts into your project is through the use of Android Studio 3.0 and above and Android 8.0

You will be leveraging the use of the design library. Include the following in your build gradle and Sync

implementation 'com.android.support:design:28.0.0'

Once done, make sure to use the app is building fine and no breakages happen.

Include the Font Resource

Great job so far, your application is ready to accept a font resource without complex and tedious wrapper classes for each Custom View. Instead, all you have to do is create a font folder like below.

Font inside res folder
Font inside res folder

The major difference between the first implementation and this is that your font folder is inside res and this will be accessible by the support library without any wrapper code.

The first implementation required a assets directory to be created and fonts folder was placed inside it.

In order to create a directory inside the res folder, right click on the res folder to find the below menu box.

creating new directory
creating a new directory

Upon clicking the new directory, a prompt to enter the directory name comes up.

Enter directory name
Enter directory name

Enter the name font to create a directory. Once done, you can place the .ttf files that we placed in the above implementation into this folder.

This loads the required Fonts and from here on, the layout implementation and Activity implementation is given.

Include it in your Layout

Including the font directly into your Layout is a bit different from what we have been seeing above. If you remember in the first implementation, the dot-separated tag was used. The same applies to this step also, but the only difference being, the dot-separated tag is already pre-written in the Support Library.

From here on we will be making use of only the below Tag. The AppCompatTextView is the TextView that can additionally take an attribute of a font family along with it.

<android.support.v7.widget.AppCompatTextView>

To include the font family along with the TextView, we will be making use of the attribute

app:fontFamily="@font/helvetica"

to the Tag. Note that, there is no android namespace, but app as its namespace. There will be a prompt to include the app namespace in your root tag if it is not already present.

The final Layout file looks like this,

<android.support.v7.widget.AppCompatTextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="SAMPLE"
    app:fontFamily="@font/courgette"/>

The above TextView creates the Text that looks like,

Final TextView
Final TextView

Include it in the Activity

Time to learn how we can load the custom font into our Activity. This is similar to what we have seen in the first implementation.

All it takes it to create an object of the AppCompatTextView and set the font to it using the public method setTypeFace().

Additionally, we will be leveraging the ResourcesCompat class loading the custom font we held in our font folder. The advantage of this method is that we can easily access the font just like we access our String. Through the R file.

See the implementation below for a clearer understanding of the same.

Typeface typeFace = ResourcesCompat.getFont(this, R.font.quintessential);
textView.setTypeface(typeFace);

Like explained above, the TypeFace object is set to ResourcesCompat’s getFont. This loads the typeface that we need to set implicitly and we will be setting it in the very next step.

The final CustomFontsSample.java looks like below

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.TypefaceCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;

public class CustomFontSample extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_custom);
        AppCompatTextView textView = findViewById(R.id.textStart);
        Typeface typeFace = ResourcesCompat.getFont(this, R.font.quintessential);
        textView.setTypeface(typeFace);
    }
}

 

Conclusion

The two implementations we saw above are very important in the aspect of setting your own Custom Fonts to your Android App. Since, custom fonts play an important aspect of material design and the paradigm surrounding it, having these two methods will be very handy.

Make sure to always have the app backward compatible and do not give a different feel when running in a lower level API’s.

Drop in any comments you have below.

“Learn and Be Curious”

Also Read  AutocompleteTextview in Android - Complete Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *