In this post, We detail how to set custom font in Android O ( API level 26) and best way of do it.
- Right click the res folder and go to New -> Android resource directory. The New Resource Directory window appears and select Font in Resource Type.
- Add font files in the Font folder.The folder structure below generates
- if we preview the fonts, double-click a font file. Next, we need to create a font family
Creating a font family
- Right click the Font folder and go to New -> Font resource file. The New Resource File window appears and enter the File name.
Each font file, style, and weight attribute in the <font>
element. The following XML illustrates adding font-related attributes in the font resource XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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/proxima_nova" /> | |
<font | |
android:fontStyle="normal" | |
android:fontWeight="400" | |
android:font="@font/proximanova_bold" /> | |
</font-family> |
Add Font in Xml file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<TextView | |
android:id="@+id/textfield2" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:fontFamily="@font/proxima_nova" /> |
Adding Fonts Programatically
getFont(int) method is used to retrieve the font programatically and provide the resource identifier of the font to retrieve and returns typeface object.
[source language=java]
Typeface typeface = ResourcesCompat.getFont(MainActivity.this,R.font.proxima_nova);
textView.setTypeface(typeface);
[/source]
so helpful 😀