22

I am using Helvetica fonts throughout my application. Currently I am creating the fonts separately from assets. So I have say these three

HelveticaNeue = Typeface.createFromAsset(application.getAssets(), "fonts/HelveticaNeue.ttf");
HelveticaNeueBold = Typeface.createFromAsset(application.getAssets(), "fonts/HelveticaNeueBold.ttf");
HelveticaNeueBoldItalic = Typeface.createFromAsset(application.getAssets(), "fonts/HelveticaNeueBoldItalic.ttf");

Everything works great when I use one typeface for one TextView. However, I need to use a spannable

Spannable WordtoSpan = new SpannableString("This text should be normal, but this needs to be bold, and normal");    
WordtoSpan.setSpan(new TypefaceSpan("bold"), 5, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

And I want to have part of the string be HeleveticaNeueBold and some be just HelveticaNeue. I think what is needed is to indicate to Android that the 3 fonts above are actually related so that it can switch them nicely. Looking for any other way of doing this as well.

Leo
  • 4,652
  • 6
  • 32
  • 42
  • Have you found answer for this question? Please share solution. I also want to use two Helvetica's fonts for ONE TextView ))) Thanks. – valerybodak Jun 12 '14 at 09:41
  • No need of custom typeface.Here is the answer [Click here](https://stackoverflow.com/questions/6612316/how-set-spannable-object-font-with-custom-font/51378290#51378290) – Himanshu Jul 27 '18 at 16:13

2 Answers2

20

You are going to want to write a custom TypefaceSpan. The good news is that they aren't difficult. See here for an example.

Community
  • 1
  • 1
Jim Baca
  • 6,112
  • 2
  • 24
  • 30
0

You can do the following:

SpannableString spannableString = new SpannableString("your text");
Typeface typeface = Typeface.create(ResourcesCompat.getFont(this, R.font.your_font);
spannableString.setSpan(
    new TypefaceSpan(typeface, Typeface.NORMAL)), 
    0, 4, 
    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

This constructor will replace the previous style of the text, achieving what you want. However, the catch is that it was introduced in API 28.

RodXander
  • 643
  • 7
  • 12