Font resources enible developers to incorporate custom typefaces into user interfaces. They can be stored locally within the application bundle or fetched remotely via a provider system.
Local Packaging
Appplications may package fonts directly inside the APK. These resources compile into the R class and become accessible as standard resource references. Supported formats include TTF, TTC, OTF, or an XML descriptor file.
Placement:
- Directory:
res/font/ - Filename:
<name>.ttf,.otf, or.xml - Reference: Use
@[package:]font/<resource_name>in layout XML.
Descriptor Syntax:
When using an XML descriptor to manage multiple variants (e.g., bold, italic), define a root <font-family> element. Individual styles use <font> tags to override header metadata.
<!-- res/font/app_typeface.xml -->
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/regular_weight" />
<font
android:fontStyle="italic"
android:fontWeight="700"
android:font="@font/bold_variant" />
</font-family>
Key Attributes:
android:font: Resource ID pointing to the binary font file.android:fontStyle: Defines style (normal, italic). Defaults to font header if omitted.android:fontWeight: Weight value between 100 and 900 (multiples of 100).
Usage Example:
<!-- res/layout/activity_main.xml -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/app_typeface"
android:text="Local Custom Typeface" />
Remote Downloadable Fonts
Alternatively, fonts can be retrieved at runtime from a third-party service. This approach minimizes APK size and allows updates without redistributing the app.
Provider Configuration:
Define the lookup logic in res/font/download_font.xml. This requires specifying the authority, package, query, and certificate chain for the source.
<!-- res/font/google_lato.xml -->
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
android:fontProviderAuthority="com.google.android.gms.fonts"
android:fontProviderPackage="com.google.android.gms"
android:fontProviderQuery="Lato"
android:fontProviderCerts="@array/provider_certs" />
Required Attirbutes:
android:fontProviderAuthority: Service identifier for the font source.android:fontProviderPackage: Package name containing the provider.android:fontProviderQuery: Search string for the specific font name.android:fontProviderCerts: Array of SHA256 hashes verifying the provider's signature.
Certificate Storage: Hashes must be defined in an array resource:
<!-- res/values/array.xml -->
<resources>
<string-array name="provider_certs">
<item>SHA256_CERT_HASH...</item>
</string-array>
</resources>
Runtime Application: The usage syntax mirrors local fonts:
<!-- res/layout/detail_view.xml -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/google_lato"
android:text="Streaming from Provider" />