3

I'm trying to assign HTML text into a TextView. Here's a sample of the HTML:

<font face="myCustomFont1">Some Text</font>
<font face="myCustomFont2">Some More Text</font>

I'm using Html.fromHtml(myHtmlString) to do this.

If the fonts are system fonts, such as sans-serif-xxx, then everything works fine. The problem is using custom .ttf / .otf files which I add to my application.

Is there a way to make fromHtml recognise custom fonts? I couldn't find anything online other than this link: Using Html.fromHtml to set custom Typeface (look at the 2nd answer - inside the comments) but it leaves the issue without an answer.

Community
  • 1
  • 1
Gil Moshayof
  • 16,633
  • 4
  • 47
  • 58
  • The accepted answer says: `No, there's no way to do so.` I wouldn't say it's **without an answer**... – Phantômaxx Jan 18 '15 at 16:19
  • Thanks, I can read. The accepted answer is wrong. I was actually looking at the 2nd answer which states that I should use the "face" attribute which works. The comments ask about custom fonts, but no answer was given. I've edited my question to make this more clear. – Gil Moshayof Jan 18 '15 at 16:20
  • `The accepted answer is wrong.` ... **really**?! – Phantômaxx Jan 18 '15 at 16:40
  • The accepted answer says "As you will see, the font tag supports size and color only" - this is wrong, since "face" is also supported and size is *not* supported. – Gil Moshayof Jan 18 '15 at 16:43
  • `face` is supported only as "internal" typefaces. – Phantômaxx Jan 18 '15 at 16:55

1 Answers1

2

Is there a way to make fromHtml recognise custom fonts?

Not for the syntax that you are proposing. You are welcome to fork the Html class and add that in. Given the way that Html is implemented, you aren't going to be able to enable this via a subclass, AFAICT.

Using a TagHandler, you may be able to pull this off without forking Html, but a TagHandler is only going to be invoked for an unrecognized HTML tag. Since <font> is recognized, the TagHandler won't be invoked for it. If you are in control over the HTML, though, you could create a <gil> tag and use that as a <font> equivalent that routes through a TagHandler that you provide. I haven't used TagHandler, which is the reason as to why I hedge as to whether this can work.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491