Android 8.0 (API level 26) introduces a new feature, Fonts in XML,
which lets you use fonts as resources. You can add the font file in
the res/font/ folder to bundle fonts as resources. These fonts are
compiled in your R file and are automatically available in Android
Studio. You can access the font resources with the help of a new
resource type, font. For example, to access a font resource, use
@font/myfont, or R.font.myfont. To use the Fonts in XML feature on
devices running Android API version 14 and higher, use the Support
Library 26.
To add fonts as resources, perform the following steps in the Android
Studio:
1.Right-click the res folder and go to New > Android resource directory. The New Resource Directory window appears.
2.In the Resource type list, select font, and then click OK. Note: The name of the resource directory must be font.
3.Add your font files in the font folder.
Creating a font family
A font family is a set of font files along with its style and weight
details. In Android, you can create a new font family as an XML
resource and access it as a single unit, instead of referencing each
style and weight as separate resources. By doing this, the system can
select the correct font based on the text style you are trying to use.
To create a font family, perform the following steps in the Android
Studio:
1.Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
2.Enter the file name, and then click OK. The new font resource XML opens in the editor.
3.Enclose each font file, style, and weight attribute in the element. The following XML illustrates adding font-related attributes
in the font resource XML:
<?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>
Using fonts in XML layouts
In the layout XML file, set the fontFamily attribute to the font file
you want to access.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
Open the Properties window to set the font for the TextView. Select a
view to open the Properties window. Note: The Properties window is
available only when the design editor is open. Select the Design tab
at the bottom of the window.
Expand the textAppearance property, and then select the font from the
fontFamily list.
Adding fonts to style
Open the styles.xml, and set the fontFamily attribute to the font file
you want to access.
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>