I'm trying to use a custom font on a TextView
. The TextView
text is set with textView1.setText(Html.fromHtml(htmlText));
The html contains bold and italic spans
Now. I purchased a custom font. The font comes with 3 different files (ttf). One for regular, one bold and for italic.
How can I apply those three font files to the textview?
This link will help you to see how to customize android font: http://mobile.tutsplus.com/tutorials/android/customize-android-fonts/
In which concerns how to apply those font files to the textview, you need to integrate them first in your project:
Typeface tf = Typeface.createFromAsset(this.getAssets(),
"fonts/xxx.TTF");
txt1.setTypeface(tf);
The ttf file should be placed in --> assets/fonts/xxx.TTF
All needed details are in the paragraph: "Using Custom Fonts"
The best way right now for API 16+ is to define a font resource file if you are using Support Library above v26 or the new AndroidX libraries, basically you add your normal and italic ttf font files in the fonts folder and create a font resource xml and basically make it look something like
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:fontStyle="normal"
app:fontWeight="400"
app:font="@font/custom_regular_font" />
<font
app:fontStyle="italic"
app:fontWeight="400"
app:font="@font/custom_italic_font" />
<font
app:fontStyle="normal"
app:fontWeight="700"
app:font="@font/custom_bold_font" />
</font-family>
the last one is for bold fonts, apply this xml suppose custom_font_family.xml to your textview as android:fontFamily="@font/custom_font_family", now any html text you set with fromHtml with any of the three span types will use the proper fonts, when needed, this allows you to even have a custom font family mixing entirely different fonts and doesn't quite literally have to be from the same family.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With