Android Custom Fonts Working with fonts in Android O

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Android O changes the way to work with fonts.

Android O introduces a new feature, called Fonts in XML, which allows you to use fonts as resources. This means, that there is no need to bundle fonts as assets. Fonts are now compiled in an R file and are automatically available in the system as a resource.

In order to add a new font, you have to do the following:

  • Create a new resource directory: res/font.
  • Add your font files into this font folder. For example, by adding myfont.ttf, you will be able to use this font via R.font.myfont.

You can also create your own font family by adding the following XML file into the res/font directory:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

You can use both the font file and the font family file in the same way:

  • In an XML file, by using the android:fontFamily attribute, for example like this:

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/myfont"/>
    

    Or like this:

    <style name="customfontstyle" parent="@android:style/TextAppearance.Small">
        <item name="android:fontFamily">@font/myfont</item>
    </style>
    
  • In your code, by using the following lines of code:

    Typeface typeface = getResources().getFont(R.font.myfont);
    textView.setTypeface(typeface);
    


Got any Android Question?