Lets say we want to use a font that is not part of the ones provided by the system.
First we create a family:
then we add the family in a text appearance style:
and finally we use the style either in our layout’s XML or through a
Everything renders correctly as long as your min SDK is 26 since this is when the fonts in xml was introduced to the framework:
When having a min SDK lower than 26 then the first thing that we need to change is our font family file. In particular we must use the app namespace instead of the android one:
Unfortunately this stops our
TextAppearanceSpan from working properly:
it renders the text with all the expected properties except the needed fonts!
Why is that?
TextAppearanceSpan, upon its construction, tries to create a typeface based on the provided font family:
getFont is added in SDK 26 and if you follow it down to resources you’ll see that it ends up in
FontResourcesParser where there is a
that tries to get the font’s name by using R.styleable.FontFamilyFont and this is where the namespace makes the difference.
So what happens when the span cannot create a typeface? In the constructor you’ll see that it loads the provided font family but only its name:
and that name is being used, when needed, to create a typeface:
The thing is that
Typeface.create loads a font only if it is a systemic one:
so anything custom does not get found and a default is being used instead.
So, at this point we know which font we want to load and we need to find a way to use the supported way of getting it.
This is one way to go. Since we know that all families live in res/font and have a .xml suffix we can clean up the name and use
getIdentifier to figure out the font’s resource id.
Now we can get the font by calling compat’s function.
What do we gain with this? We can simply replace
FontAwareTextAppearanceSpan and have our entire project use the new font with the minimum number of changes: