How to change the font across the whole app

Either for the branding or to make the app look cooler or different, you might wonder how to change the font across the whole app? And all this in one go, without setting something for each view. So let’s do a step by step with this.

I made a simple app that has a list of articles from floridaman.com (some of the articles are quite funny) and a details screen for the article that it looks like this:

Step 1. Download the font

Once you picked your font, download it and you should have a folder with a lot of .ttf files like this:

Step 2. Adding font to project

For this demo I picked just two fonts and renamed them:

  • SourceCodePro-Regular to source_code_pro_regular
  • SourceCodePro-Italic to source_code_pro_italic

Now we will go in Android Studio to the res folder, right-click on it, and create a new Android Resource Directory

And when the Dialog pops up we will choose to create a font directory

Now we take our fonts and copy them in the newly created font directory. The result should look like this.

Step 3. Creating the font family resource

For that, we right-click on the font directory in Android Studio and create a new resource file, that will have the root as font-family. Something like this:

I named it default_font, because it will be a default everywhere in the app, and know we should tell them what font to use, so we change the content of the XML file to this:

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

Basically we set the font and pick the style for each font. There is also a font-weight attribute in case you need that.

Now you might notice a warning in the XML file and if you hover over it you will see that it says:

Attribute font is only used in API level 26 and higher

So this will only work for API level 26 or higher. To fix that we can click on the warning suggestion and choose to override Resource in font-v26. This will create a folder with two default_font.xml files. One for API level 26 and higher and the other one for below API level 26.

Now the one with the (v26) we will leave it as it is and on the other one we will replace android: namespace with the app: namespace in order to take advantage of the Support Library that can set the font below API level 26. More details you can find here.

<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:app="http://schemas.android.com/apk/res-auto"> <font app:font="@font/source_code_pro_regular" app:fontStyle="normal" /> <font app:font="@font/source_code_pro_italic" app:fontStyle="italic" /> </font-family>

Step 4. Setting the font in the app

<item name="android:fontFamily">@font/default_font</item>

Now if you run the app the result will look like this:

Conclusion