Custom Fonts using Support Library

One of the most exciting announcements by Google in I/O 17 was providing support for custom fonts. Not as an asset but fonts can now be used as a resource. An application can also use one of many Google Fonts dynamically. As fonts are now supported natively, the same font can be used by different applications.

The feature is extended to support API version 14 and above through Support Library 26. Below is a brief overview of how fonts are used by applications:

Fig. 1.0 Downloadable Fonts process

FontContract is a Utility class that deals with Font Content Provider. Downloaded Fonts are cache within the device. Since multiple devices share a single endpoint for fonts. Hence, fonts are shared across different applications.

Advantages of using Downloadable fonts:

  • Reduced APK size. As fonts are no longer needed to be kept in APK.
  • Fonts are shared by different applications through a single provider. Hence it saves phone memory and user data. Fonts are downloaded only when they are needed.

Where Downloadable fonts might not work:

  • Fonts may fail to load/download depending upon network connection, in which case default font are used.
  • Downloadable fonts require a Font Provider, for eg. Google Fonts are provided by Google Play Services.

With Support Library and Android O, Fonts can be used with these two features:

  • Fonts as a Resource
  • Downloadable fonts

Let us deep dive into each of these separately.

You can find the code for this blog here.

Fonts as a Resource

Creating a new project in Android Studio 3.0, we can see a ‘font’ directory in our ‘res’ folder. We can add our custom fonts(ttf and otf) in this directory and can use them in the project like we use other resources. More than that, you can also create font family where you can define different fonts with styles and weights.

Fig. 1.1 Font Resource Directory

The Ubuntu font can be directly used in a View like AppCompatButton, AppCompatTextView using ‘fontFamily’ tag as below:

[code language=”xml”]

[/code]

Or you can use ‘getFont’ method in O to get font resource as below:

[code language=”java”]
Typeface typeface = getResources().getFont(R.font.ubuntu_bold);
[/code]

Note: getFont() is supported by API 26 and above. You may have to go with XML approach for the older device.

For creating fontFamily with different styles and weight, like I have created one for normal and italic style types.

[code language=”xml”]
open_sans_font_family.xml

[/code]

A font family can be used in similar way as we have used with the AppCompatButton in above case.

You can also use a font throughout the application by adding it to app style.

[code language=”xml”]
styles.xml

@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
@font/open_sans

[/code]

Downloadable Fonts

The fonts are no longer supposed to be a bundled with the apk, but instead, they are downloaded on demand from Font Provider when are needed by an Application. If other apps in the system use the same font the fonts are reused. In case fonts fail to download, then default system fonts are used.

Let’s see how simple it is to implement a font provider using XML.

In layout editor attributes, we can find a fontFamily property of the view (AppCompatTextView in our case). Clicking on the drop-down, we will see More Fonts.. option in the bottom.

Fig. 1.2 Font Family view property

We will this dialog after selecting More Fonts option from where we can pick any of the google fonts from there and the studio will set up everything for us!

Fig. 1.3 More Fonts Dialog

Downloadable fonts as XML Resource

[code language=”xml”]
open_sans.xml

[/code]

1. The fontProviderAuthority provides with a unique URL that is used to interact with the Font Provider.

2. The fontProviderPackage name is the root package name of the FontProvider. It can also be considered as a Base URL.

3. The fontProviderQuery contains the params of a font to be used like name, weight, style etc. Like:

name=Open Sans&weight=700&width=75

You can read more about query syntax and formatting from here: Query Format

4. The fontProviderCertificate is the certificate the Font Provider was signed with.

[code language=”xml”]
open_sans.xml
<?xml version="1.0" encoding="utf-8"?&gt;

@array/com_google_android_gms_fonts_certs_dev
@array/com_google_android_gms_fonts_certs_prod

[/code]

Note: Android Studio can automatically populate the values for the Google Play services provider if you use the font selector tool in Android Studio.

Pre-declaring fonts in the manifest

Fonts are loaded Synchronously when the layout using it is inflated. Fonts can be preloaded by declaring them in the manifest using meta tag.

We put all the fonts that are to be downloaded in a resource array. Here all font elements are downloadable resources as we have seen above.

[code language=”xml”]
preloaded_fonts.xml

@font/open_sans
@font/open_sans_bold
@font/open_sans_condensed_bold
@font/open_sans_extrabold
@font/open_sans_light
@font/open_sans_semibold

[/code]

and then we add meta-data tag in the manifest to declare them.

[code language=”xml”]
AndroidManifest.xml



[/code]

Also, one can add async fetch strategy and fetch timeout in the font family.

[code language=”xml”]
open_sans.xml

[/code]

Using Downloadable Fonts programmatically

Fonts can be downloaded dynamically using Java/Kotlin code. We start by creating a FontRequest. A FontRequest requires a provider authority, provider package, font query and certificate array. Parameters are same as of the XML parameters.

[code language=”java”]
class Activity:AppCompatActivity() {
….
private var regular: AppCompatTextView? = null
private val certificate = R.array.com_google_android_gms_fonts_certs

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_labels_no_fonts)
regular = findViewById(R.id.tv_regular)


val sansRegularRequest = FontRequest(Companion.PROVIDER_AUTHORITY, PROVIDER_PACKAGE, “Open Sans”, certificate)
val sansRegularCallback = object : FontsContractCompat.FontRequestCallback() {
override fun onTypefaceRetrieved(typeface: Typeface?) {
// Called When fonts are loaded/downloaded
regular!!.typeface = typeface
}
override fun onTypefaceRequestFailed(reason: Int) {
// Called When fonts fail to loaded/downloaded, Here reason is the error code
// Read more about reasons from here:
// https://developer.android.com/reference/android/provider/FontsContract.FontRequestCallback.html#FAIL_REASON_FONT_LOAD_ERROR
}
}
FontsContractCompat.requestFont(this, sansRegularRequest, sansRegularCallback, Handler())
}

companion object {
private val PROVIDER_PACKAGE = “com.google.android.gms”
private val PROVIDER_AUTHORITY = PROVIDER_PACKAGE + “.fonts”
}
}
[/code]

As a callback to FontRequest, we use FontsContract.FontRequestCallback object, that provides us with two callback methods to handle FontRequest responses.

onTypefaceRetrieved method is called when the font is downloaded. It provides with a TypeFace object of the requested font.

onTypefaceRequestFailed method is called when the queried font fails to load, the method argument provides with an int error code for reason of failure. You can read about various error codes here.

FontsContractCompat.requestFont method is used to make request of font.

Note: The last argument of FontsContractCompat.requestFont takes a handler thread as an input, just make sure that it isn’t a UI thread.

And here is the final app after implementing all weighted fonts.

 

Fig 1.4 Final App Screenshot

 

Remarks

I personally think this will actually make it easier to develop highly customized apps in a better way. Gone are the days when all fonts were a part of app assets.

 

Fig. 1.5 Some Old Memories

 

 

We cannot ignore the fact that fonts are executable, hence they come with their own security risks.


Posted

in

by

Comments

Leave a Reply

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