I have a custom TextView
, to show html text. For pre-Nougat devices it works. As you already know on Nougat, fromHtml is deprecated and it needs a flag..so my code is like this
Spannable s = getRichText(text);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
super.setText(Html.fromHtml(s.toString(), Html.FROM_HTML_MODE_COMPACT, this, new HtmlHandler(getContext())), BufferType.SPANNABLE);
} else {
super.setText(Html.fromHtml(s.toString(), this, new HtmlHandler(getContext())), BufferType.SPANNABLE);
}
The problem it that, the HtmlHandler
class is never get called. (I have already tried all the flags).
On HtmlHandler
I handle tags and styles, eg background-color
, color
et cetera. I have implemented to get colors from rgb
, rgba
, hls
etc. But on Nougat it accepts only colors with hex, because on Nougat, fromHTML
can "read" colors and show them. Why is this happening? How can I keep my way for the colors? If you didn't understand something, or need more details, let me know.
The html I use for testing is
<p><strong>Server</strong><u> message</u><strong><u>!!!</strong></u> <span style="background-color: rgb(255,0,0);">Not working on Nugat</span></p>
Html.fromHtml()
will only invoke your TagHandler
for HTML tags that fromHtml()
does not recognize. In your sample HTML, you have:
<p>
<strong>
<u>
<span>
and in your first comment, you also mention div
.
Of those, fromHtml()
has handled <p>
, <strong>
, and <u>
since at least 2010, if not earlier. fromHtml()
in Android 6.0 also handles <div>
(see lines 488-489 in the source), and I forget how back that support goes. Your TagHandler
would not be called for any of these tags, and that behavior is not especially new.
Android 7.0 added support for <span>
(see lines 804-805 from the 7.1 source), and so code that expected a TagHandler
to be invoked for <span>
would behave differently between Android 7.0 and previous versions.
In general, the list of supported tags is undocumented. Google is welcome to change the roster of supported tags at any point.
Your options are:
Live with it
Grab the source to some Html.java
that you like, refactor it into your own package, and use that copy, modifying it as you see fit
Find some other HTML-to-Spannable
source code that you like better