android – How to create custom font family with bold font-ThrowExceptions

Exception or error:

I’m trying to create custom font family using this doc https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html The problem in that that there is no bold attribute and I can not set it programmatically Fonts in XML?

How to solve:

Set 700 as the fontWeight value for your font in bold.

As it’s in the font resources documentation:

The most common values are 400 for regular weight and 700 for bold
weight.

In the lobster font family example you linked it would be:

<!-- bold -->
<font
    android:fontStyle="normal"
    android:fontWeight="700"
    android:font="@font/lobster_bold" />

And, if you are using support lib:

<!-- bold -->
<font
    app:font="@font/lobster_bold"
    app:fontStyle="normal"
    app:fontWeight="700" />

###

In addition to @jeprubio answer, I should add this that if you are using one font family resource for different font style

for example you got serif_normal.ttf & serif_bold.ttf fonts and have one font
family resource named serif_font.xml like this:

<?xml version="1.0" encoding="utf-8"?>

<font
    android:font="@font/serif_normal"
    android:fontStyle="normal"
    android:fontWeight="400"
    app:font="@font/serif_normal"
    app:fontStyle="normal"
    app:fontWeight="400" />

<font
    android:font="@font/serif_bold"
    android:fontStyle="normal"
    android:fontWeight="700"
    app:font="@font/serif_bold"
    app:fontStyle="normal"
    app:fontWeight="700" />

for referring to the bold weight or normal you can use

android:textStyle=”normal | bold”

or you can create a custom style like this :

<style name="TextAppearance.BoldFond" parent="android:TextAppearance">
    <item name="android:fontFamily">@font/sarif_font</item>
    <item name="fontFamily">@font/sarif_font</item>
    <item name="android:textStyle">bold</item>
    //another attributes
</style>

checkout Here for full description.

###

Download roboto bold font from
Robot Font URL

and paste this font file in res>font folder .

now you can use this font in xml like this way

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/robot_bold" />

You can also set a simple font and set android:textStyle="bold" to bold the text

Leave a Reply

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