Use custom font in style attribute

16,406

There isn't a way to do it straight out of the box. There's a library called Calligraphy that will let you do it. It will work on API 7+

I've also seen a trick using reflection to override serif/sans so that you can define those in your styles.xml: Is it possible to set a custom font for entire of application?, though I would recommend the first approach.

Share:
16,406
Tomasz Madeyski
Author by

Tomasz Madeyski

Senior Developer at Forte_ Digital

Updated on July 28, 2022

Comments

  • Tomasz Madeyski
    Tomasz Madeyski almost 2 years

    What I want to achieve is adding style attribute to my axml file with custom font loaded from Asset.

    I know I can load built-in fontface like this (style.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
      <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:typeface">monospace</item>
      </style>
    </resources>
    

    And use it (Main.axml):

    <TextView
            style="@style/CodeFont"
            local:MvxBind="Text Hello" />
    

    I know that I can also create MyCustomTextView extending TextView and setting font by SetTypeface method, but I would like to use custom font in style attribute.

    So something like:

     <resources>
        <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
          <item name="android:typeface">MyCustomFontLoadedFromAsset</item>
        </style>
     </resources>
    

    Is it possible (and how to do it)?